Search code examples
reactjsscrollheadertailwind-cssnavbar

How to make a header in react have a shadow only on scroll using tailwindcss?


I have a header in react that I want to have no shadow when the scrollbar position is initial (0), and on scroll, to have a shadow. Here is the code to the header with and without a shadow using tailwindCSS:

With shadow:

<header className="sticky left-0 top-0 right-0 z-20 shadow">
...
</header>

Without shadow:

<header className="sticky left-0 top-0 right-0 z-20">
...
</header>

How can I check if the scrollbar is not in its initial position to make the header take the className "shadow"?


Solution

  • A simple solution to your question is to create a state to check if the screen has been scrolled, update the state with a useEffect once the screen is scrolled and then add the shadow class to the header if the screen has been scrolled. Here is how I achieved it:

    const [top, setTop] = useState(true);
    
    useEffect(() => {
      const scrollHandler = () => {
        window.scrollY > 10 ? setTop(false) : setTop(true)
      };
      window.addEventListener('scroll', scrollHandler);
      return () => window.removeEventListener('scroll', scrollHandler);
    }, [top]);
    
    

    Then your header class would look like this:

    <header className={`sticky left-0 top-0 right-0 z-20 ${!top && `bg-white shadow-lg`}`}>