Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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';
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
430 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...