Media query syntax for Reactjs Media query syntax for Reactjs reactjs reactjs

Media query syntax for Reactjs


You can make media queries inside React:

import React, { Component } from 'react';class App extends Component {  constructor(props) {    super(props)    this.state = { matches: window.matchMedia("(min-width: 768px)").matches };  }  componentDidMount() {    const handler = e => this.setState({matches: e.matches});    window.matchMedia("(min-width: 768px)").addEventListener('change', handler);  }  render() {    return (      <div >      {this.state.matches && (<h1>Big Screen</h1>)}      {!this.state.matches && (<h3>Small Screen</h3>)}      </div>    );  }}export default App;

https://stackblitz.com/edit/react-cu8xqj?file=src/App.js


09-10-2021 Edit: replaced addListener with addEventListener as former was deprecated. Thanks to John Galt for letting us know by posting a comment.


You cannot set media queries inline. You will need to create a separate CSS stylesheet and then import the stylesheet.

So the following code would go in a new styles.css file for example.

.heading {  text-align: right;  /* media queries */  @media (max-width: 767px) {    text-align: center;  }  @media (max-width: 400px) {    text-align: left;  }}

Then you can import your new CSS styles file into your react file. For example, you could add import './styles.css' to the top of your App.jsx file (assuming they are both at the root level), or you could import it directly into a specific react component file.


If you have a special cases, when you need to get media query result inside you react app (for example, you want to show some component at mobile version), you can use helpers like react-responsive or react-media-hook.