Redux changing state according to window width

Viewed 68

I have an aside menu which i wanted to be closed if window width is smaller than 768 and I can do it with this code in reducer:

case "SCREEN_RESIZE":
if(action.screenWidth <= 768) {
  return {...state, changeHamburger: state.changeHamburger = false}
} else {
  return {...state, changeHamburger: state.changeHamburger = true}
}

And I attached dispatch to both a resize and a onload event:

const disPatchFunc = () => {
  dispatch(screenResize(window.innerWidth));
}
    
window.addEventListener("load", disPatchFunc);
window.addEventListener("resize", disPatchFunc);

My problem is, whenever the window width is smaller than 768, the menu is closed but when I opened the menu and changing the browser width size. It has closed again because the condition in the reducer is working obviously.

How can I manage not to close on resize in smaller than 768px condition states?

1 Answers

You can add a flag called isMenuOpenedManually set it to false by default. In click event function of hamburger icon change the state of isMenuOpenedManually according to following cases:

1) Screensize <= 768 && Menu is opened manually -> isMenuOpenedManually = true;
2) Screensize <= 768 && Menu is closed manually -> isMenuOpenedManually = false;

I might have missed some case but you might have got some idea to handle it. Hope this solves your problem.

Related