Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Media query syntax for Reactjs

How do I do the following CSS media query in Reactjs?

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

I tried the following but it throws a syntax error and fails to compile.

heading: {   textAlign: 'right',   @media (maxWidth: '767px') {     textAlign: 'center';   }   @media (maxWidth: '400px') {     textAlign: 'left';   } } 
like image 360
Let Me Tink About It Avatar asked Feb 02 '19 09:02

Let Me Tink About It


People also ask

How do you do a media query in React?

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. Show activity on this post. Show activity on this post. You cannot set media queries inline.

Does media query work in React?

Step 7: Finally we can use media queries in our react component example. js. In this example, we have added a query if the width of the device is less than 501px then our app will display nothing.

How do you declare a media query?

Media Query SyntaxA media query consists of a media type and can contain one or more expressions, which resolve to either true or false. The result of the query is true if the specified media type matches the type of device the document is being displayed on and all expressions in the media query are true.

How do you use media query in material UI React?

To add media queries in React Material UI components, we can call makeStyles with a function that takes the theme parameter. Then we can get the breakpoints from theme and use them as properties for applying styles for different screen sizes.


1 Answers

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.

like image 165
ferit Avatar answered Sep 19 '22 14:09

ferit