Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React and Matchmedia

I'm using react context API in component did mount to set methods. I'd also like to use the media query there and set a method to open or close the sidenav depending on screen size.

Something like this

 componentDidMount() {
    let context = this.context;
    let path = this.props.pageContext && this.props.pageContext.path;
    context.setSidenavLeaf(newPath)

// Below this is where I'd like to use the media query to set the sidenavOPen to false. Just not sure how to achieve that
  const match = window.matchMedia(`(max-width: 768px)`) 
if(match {
context.setSidenavOpen(false)
  }
}

Kind of confused about how to achieve something like this. I want to call the method and set it at a specific media break point in my component did mount. Which is using react router path prop. So if I hit that specific url rendered by that component and the screen size is such, close the sidenav else leave it open.

like image 887
AnneJoday Avatar asked Jul 03 '26 04:07

AnneJoday


1 Answers

You need to listen for resize event:

 componentDidMount() {
    let context = this.context;
    let path = this.props.pageContext && this.props.pageContext.path;
    context.setSidenavLeaf(newPath);

    // Below this is where I'd like to use the media query to set the sidenavOPen to false. Just not sure how to achieve that
    this.checkWidth = () => {
      const match = window.matchMedia(`(max-width: 768px)`);
      if (match) {
        context.setSidenavOpen(false);
      }
    };

    this.checkWidth();
    window.addEventListener("resize", this.checkWidth);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.checkWidth);
  }

or add listener to the media query itself:

componentDidMount() {
    let context = this.context;
    let path = this.props.pageContext && this.props.pageContext.path;
    context.setSidenavLeaf(newPath);

    // Below this is where I'd like to use the media query to set the sidenavOPen to false. Just not sure how to achieve that
    this.match = window.matchMedia(`(max-width: 768px)`);
    this.checkWidth = (e) => {      
      if (e.matches) {
        context.setSidenavOpen(false);
      }
    };

    this.checkWidth(this.match);
    this.match.addListener(this.checkWidth);
  }

  componentWillUnmount() {
    this.match.removeListener(this.checkWidth);
  }
like image 85
marzelin Avatar answered Jul 05 '26 18:07

marzelin