3

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?

Arte
  • 397
  • 1
  • 4
  • 14
  • Possible duplicate of [JavaScript window resize event](https://stackoverflow.com/questions/641857/javascript-window-resize-event) – Agney May 11 '19 at 07:35

2 Answers2

3

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.

vlad-grigoryan
  • 322
  • 3
  • 11
1

You need an event listener to watch for changes in the window, specifically, you want to listen for the resize event.

const handleResize = () => {
  // put your logic here
  console.log(window.innerWidth)
}

window.addEventListener('resize', handleResize)

That will output the inner width of your window as you resize it.

bntzio
  • 1,274
  • 14
  • 27