Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 346
Kevin Nammour Avatar asked May 07 '26 08:05

Kevin Nammour


1 Answers

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 = () => {
    setTop(window.scrollY <= 10)
  };
  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`}`}>
like image 140
Akugbe Stephen Avatar answered May 09 '26 01:05

Akugbe Stephen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!