Search code examples
jsxgatsbystyled-components

Updating CSS of Styled Component on Scroll in React


I have a Wrapper component in index.jsx as follows:

export const Header = () => {
  const [sidebar, toggle] = useState(false);

  return (
    <Wrapper>
      <Overlay sidebar={sidebar} onClick={() => toggle(!sidebar)} />
      <Navbar />
      <Hamburger sidebar={sidebar} toggle={toggle} />
      <Sidebar sidebar={sidebar} toggle={toggle} />
    </Wrapper>
  );
};

And it has been styled using styled-component in style.js as follows:

export const Wrapper = styled.div`
  background: transparent;
  width: 100%;
  position: fixed;
`;

I am new to React and trying to figure out how I can update the CSS of Wrapper on the scroll event. After a bit of research, I read about componentDidMount() and useEffect() but I am unsure how to use those in jsx.


Solution

  • So, I found out that we can actually use props in the styled-components in the following manner:

    const Wrapper = styled.div`
      background: ${({ scrolled }) => scrolled > 300 ? '#212121' : 'transparent'};
      width: 100%;
    `;