Home > front end >  Update state according to screen size on load and on screen resize
Update state according to screen size on load and on screen resize

Time:01-12

The function is supposed to change the navigation bar when there is a resize and on load. The problem is it doesn't work immediately.

On chrome devtools, it triggers after 1 second; on a few mobiles, I've tested it, and it works after scrolling down to the bottom or rotating the screen and coming back.

const [mobile, setMobile] = useState(false);

const handleResize = () => {
        if (window.innerWidth <= 468) {
            setMobile(true);
        } else {
            setMobile(false);
        }
    };

    window.addEventListener('load', handleResize);
    window.addEventListener('resize', handleResize);

 return (
        <nav
            className={
                navColor
                    ? css.nav__container
                    : `${css.nav__container} ${css.nav__blur}`
            }>
            <a
                href='#'
                onClick={() => setActiveNav('#')}
                className={activeNav === '#' ? css.nav__active : ''}>
                {mobile ? <RiHome3Line /> : 'Home'}
           </a>
       </nav>

I tried to change const to function(); I expect it to work on load, not after some time.

CodePudding user response:

You could use only resize with an useEffect to have something more React-like. Here is an example:

const [mobile, setMobile] = useState(false);

useEffect(() => {
  const handleResize = () => {
    if (window.innerWidth <= 468) {
      setMobile(true);
    } else {
      setMobile(false);
    }
  };
  // runs on load
  handleResize();
  // runs when the screen size changes
  window.addEventListener("resize", handleResize);
  // remove the event listener before the component gets unmounted
  return () => window.removeEventListener("resize", handleResize);
}, []);
  • Related