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
There are multiple ways to archive this first way is with CSS using this class
@media screen and (max-width: 576px) {}
any class inside this tag will only be visible when the screen is equal or less than 576px
the second way is to use the event listener
something like this
constructor(props)
{
super(props);
this.state = {
isToggle: null
}
this.resizeScreen = this.resizeScreen.bind(this);
}
componentDidMount() {
window.addEventListener("resize", this.resizeScreen());
}
resizeScreen() {
if(window.innerWidth === 576)
{
this.setState({isToggle:'I was resized'});
}
}
even with the event listener I still prefer the CSS way since we can use multiple screen sizes without further js coding.
I hope this helps!