I am developing a web app with React and need to detect when the screen size has entered the mobile break-point in order to change the state. Specifically I need my sidenav to b
This is the same as @Ben Cohen answer but after attaching your function to eventListner, also remove it on componentWillUnmount
constructor() {
super();
this.state = { screenWidth: null };
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}
componentDidMount() {
window.addEventListener("resize", this.updateWindowDimensions());
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateWindowDimensions)
}
updateWindowDimensions() {
this.setState({ screenWidth: window.innerWidth });
}