5

I am building a gatsby site and I want to have my header change background color opacity as I scroll down. What's the best way to approach this?

I currently have this, where isScrolled is a state value that I'm updating with a custom hook. The problem I have is that there is no transition appearing, I'm pretty sure because React is re-rendering the whole component when the state changes.

What would be the appropriate tool / method for solving this problem?

 <header
          className={
            `h-16 z-10 fixed top-0 left-0 w-screen transition-all`
              ${
               isScrolled ? "bg-white" : "bg-transparent"
             }`
          }
        >
          <div className="px-8 container mx-auto flex items-center justify-between h-full">
            <Logo />
            <nav>
              <HeaderLink to="about-us">About</HeaderLink>
              <HeaderLink to="blog">Blog</HeaderLink>
              <HeaderLink to="contact">Contact</HeaderLink>
            </nav>
          </div>
        </header>

I've tried the HeadlessUI Transition component but that doesn't work because it only transitions in an entire component (as opposed to a property) and I haven't been able to get React-Transition-Group working either. Any help would be appreciated,

Thanks

Raph117
  • 3,441
  • 7
  • 29
  • 50

1 Answers1

8

try use this in your component,

...
const [isScrolled, setIsScrolled] = useState(false);
...
  <header
    className={`h-16 z-10 fixed top-0 left-0 w-screen transition-all duration-200
          ${isScrolled ? "bg-white" : "bg-transparent"}`}
  >

and read this article to detect the correct scroll event. Happy coding!

JsWizard
  • 1,663
  • 3
  • 21
  • 48