Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check screen size change for a specific width

I have a solution that checks the current width of the screen, and depending on the results load the normal desktop menu or hamburger menu.

However, if a user decreases (or increases for that matter) the current window, it will not reload the correct menu for that new size without forcing the user to update the window as well. My code looks like this:

let width = window.innerWidth;

if (window.matchMedia("(orientation: landscape)").matches && width < 1025) {
  return (
    <MegaMenuContainer provider={provider} /> // hamburger
  );
}
else if (width > 1025) {
  return (
    <MegaMenuContainerDesktop provider={provider} />
  );
}
else {
  return (
    <MegaMenuContainer provider={provider} />  //Hamburger
  );
}

So if the current size is 1025, the desktop menu should be loaded. And when the user resize it below 1025, it should trigger the hamburger version (with maybe a this.forceUpdate()).

I probably need an eventlistener to check if the screen has been resized and check the initial width, compare it if its lover or higher than 1025 and load the correct menu. How to do that?

like image 409
Arte Avatar asked Feb 27 '26 21:02

Arte


1 Answers

Your Component can be like this:

class WindowDimensions extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      innerWidth = window.innerWidth
    }
  }
  handleResize = () => {
      this.setState({innerWidth: window.innerWidth);
  }

  componentDidMount() {
      window.addEventListener("resize", this.handleResize);
  }

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

  render() {
    const innerWidth = {state};
    if (window.matchMedia("(orientation: landscape)").matches && innerWidth < 1025) {
      return (
        <MegaMenuContainer provider={provider} /> // hamburger
      );
    }
    else if (innerWidth > 1025) {
      return (
        <MegaMenuContainerDesktop provider={provider} />
      );
    }
    return (
      <MegaMenuContainer provider={provider} />  //Hamburger
    );
  }
};

Don't forgot unsubscribe from resize listener.

like image 125
vlad-grigoryan Avatar answered Mar 01 '26 09:03

vlad-grigoryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!