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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.