Luke
Luke

Reputation: 73

Styled Components: pass a state on scroll

I'm trying to pass a prop to a styled component on scroll, but it doesn't seem to have any effect (even though the scroll listener works). Does anyone see where I'm going wrong?

const Box = styled('div')(  
  `
  ${props => props.scroll && css`
      background-color: pink;
    `};

  `
);

const [scroll, setScrolled] = useState(false);

  const scrollHandler = useCallback(() => {
    if (window.pageYOffset > 100) {
      setScrolled(true);
    }


    if (window.pageYOffset < 100) {
      setScrolled(false);
    }
  }, []);

  useEffect(() => {
    window.addEventListener('scroll', scrollHandler);
  }, [scrollHandler]);


return(
    <Box scroll={scroll}>test</Box>
)

Upvotes: 0

Views: 726

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

There is nothing wrong with how you use styled-component which is the primary question.

What might not work is your event listener, you should listen to element's onScroll event instead of global window which can have some unexpected results, here is a working example:

const Box = styled.div`
  background-color: ${({ scroll }) => (scroll ? `palegoldenrod` : `pink`)};
  height: 100px;
  overflow: auto;
`;

export default function App() {
  const [scroll, setScrolled] = useState(false);

  useEffect(() => {
    setTimeout(() => { setScrolled(false) }, 1000);
  }, [scroll]);

  return (
    <Box
      scroll={scroll}
      onScroll={() => {
        setScrolled(true);
      }}
    >
      <span>
        Lorem ipsum faucibus facilisis per nisi pharetra vel, rhoncus mattis
        scelerisque consequat fermentum integer, mauris varius orci facilisis
        aptent dictumst orci quis urna semper mollis risus. Sit tristique tempus
        posuere pharetra morbi felis et duis quisque convallis est, quisque
        tellus magna eleifend sed augue nulla dolor consequat accumsan, netus
        elementum luctus eget interdum quisque tempor euismod sem donec.
        Habitasse class aliquam risus non lacinia a scelerisque vivamus
        fermentum, consequat scelerisque diam nibh volutpat eros sociosqu
        praesent pretium tristique, nisl curae malesuada vestibulum etiam purus
        curabitur arcu. In nostra torquent porttitor varius nam nisl ornare,
        aptent amet sit erat dolor platea, imperdiet at bibendum euismod
        condimentum ut interdum id eleifend eu eros semper cubilia sagittis.
        Praesent diam pretium class nostra semper augue nulla senectus
        adipiscing aliquet, habitant nisi lacinia ultricies aenean orci
        condimentum posuere et sollicitudin eu aenean placerat feugiat nibh duis
        proin curae.
      </span>
    </Box>
  );
}

Edit onScroll

Upvotes: 1

Related Questions