3

I have been trying to make this tailwind navbar component for react (code obtained from site) close on scroll for mobile view but am not been able to make it work.=>>> codesandbox link

I tried implementing the following code obtained from another thread but its still not working. Someone please help.

import React, { useState, useEffect } from 'react';

const Navbar = () => {
  const [show, setShow] = useState(true);
  const [lastScrollY, setLastScrollY] = useState(0);

  const controlNavbar = () => {
    if (typeof window !== 'undefined') { 
      if (window.scrollY > lastScrollY) { // if scroll down hide the navbar
        setShow(false); 
      } else { // if scroll up show the navbar
        setShow(true);  
      }

      // remember current page location to use in the next move
      setLastScrollY(window.scrollY); 
    }
  };

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.addEventListener('scroll', controlNavbar);

      // cleanup function
      return () => {
        window.removeEventListener('scroll', controlNavbar);
      };
    }
  }, [lastScrollY]);

  return (
        <nav className={`active ${show && 'hidden'}`}>
        ....
        </nav>
  );
};
Akshay Benny
  • 69
  • 1
  • 11

1 Answers1

0

You don't need the setShow(true) in the controlNavbar function. Otherwise you just keep re-opening the navbar for no reason.

const controlNavbar = () => {
  if (typeof window !== 'undefined') { 
    if (window.scrollY > lastScrollY) { // if scroll down hide the navbar
      setShow(false); 
    } else {
      setShow(true);  
//    ^^^^^^^^^^^^^^ Remove this line
    }

    // remember current page location to use in the next move
    setLastScrollY(window.scrollY); 
  }
};

And it's better to follow the eslint exhaustive-deps rules. So the code will be refactored to:

const controlNavbar = useCallback(() => {
  if (typeof window !== 'undefined') {
    if (window.scrollY > lastScrollY) {
      // if scroll down hide the navbar
      setIsOpen(false);
    }
    // remember current page location to use in the next move
    setLastScrollY(window.scrollY);
  }
}, [lastScrollY]);

useEffect(() => {
  if (typeof window !== 'undefined') {
    window.addEventListener('scroll', controlNavbar);

    // cleanup function
    return () => {
      window.removeEventListener('scroll', controlNavbar);
    };
  }
}, [controlNavbar]);
CodinCat
  • 15,530
  • 5
  • 49
  • 60