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'; } }
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With