Search code examples
javascriptcssreactjsjsxstyled-components

Target specific class using Styled Components React.js


I am trying to add a theme to a navbar component. This component has a function for a sticky navbar to appear when scrolling down. I'm really stuck on targeting the 'sticky' class once the window is scrolled down. This worked with normal css but once I added it to the styled-component and removed it from the css its not working.

Maybe I'm not targeting the className 'sticky' correctly?

Any suggestions?? Thank you!

    export function Nav() {
      const [theme, setTheme] = useState("light");
      const [theTheme, setTheTheme] = useGlobal("onTheme");

      useEffect(() => {
        if (theTheme == false) setTheme("dark");
        else setTheme("light");

   
        window.addEventListener("scroll", function () {
        var header = document.querySelector("header");
        header.classList.toggle("sticky", window.scrollY > 0);
    });
  });

  return (
    <ThemeProvider theme={getTheme(theme)}>
      <Head>
        <Navbar>
          <NavLink></NavLink>
          <NavItem icon={<CaretIcon />}>
            <DropdownMenu />
          </NavItem>
        </Navbar>
      </Head>
    </ThemeProvider>
  );
}

I can target the 'sticky' class using normal CSS.

    header.sticky {
      background-color: rgb(31, 31, 37);
    }

I am trying to target 'sticky' using Styled Components.

    export const Head = styled.header`
      position: fixed;
      width: 100%;
      background-color: transparent;
      top: 0rem;
      transition: 0.6s;
      z-index: 100000;
      text-decoration: none;
      & .sticky {
        background-color: ${(props) => props.theme.hoverColor};
       } 
     `;

Solution

  • Looks like one unnecessary space between & .sticky ends up with applying for children instead of the header itself. The correct one is supposed to be:

    export const Head = styled.header`
      position: fixed;
      width: 100%;
      background-color: transparent;
      top: 0rem;
      transition: 0.6s;
      z-index: 100000;
      text-decoration: none;
    
      &.sticky {
         background-color: ${(props) => props.theme.hoverColor};
      } 
    `;