1

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};
       } 
     `;

1 Answer 1

3

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};
  } 
`;
Sign up to request clarification or add additional context in comments.

1 Comment

WOW I feel so dumb! Thank you so much it now works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.