AnneJoday
AnneJoday

Reputation: 99

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.

Upvotes: 3

Views: 10598

Answers (2)

Andy
Andy

Reputation: 11462

for functional components, there's a hook on github that will do this for you https://www.npmjs.com/package/react-simple-matchmedia

Upvotes: 0

marzelin
marzelin

Reputation: 11600

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);
  }

Upvotes: 2

Related Questions