Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start animation in react-spring when component is in view

I am using react-spring for animation and all the animations start once the page is loaded. I want to control the start of the animation. The desired outcome is to let the components down in the screen start the animation once they are in view (i.e the user scrolled down). The code follows something like this :

const cols = [
/*Components here that will be animated ..*/
{component: <div><p>A<p></div> , key:1},
{component: <div><p>B<p></div> , key:2},
{component: <div><p>C<p></div> , key:3},

]

export default function foocomponent(){
  const [items, setItems] = React.useState(cols);
  const [appear, setAppear] = React.useState(false); // Should trigger when the component is in view

  const transitions = useTransition(items, (item) => item.key, {
    from: { opacity: 0, transform: 'translateY(70px) scale(0.5)', borderRadius: '0px' },
    enter: { opacity: 1, transform: 'translateY(0px) scale(1)', borderRadius: '20px', border: '1px solid #00b8d8' },
    // leave: { opacity: 1, },
    delay: 200,
    config: config.molasses,
  })


  React.useEffect(() => {
    if (items.length === 0) {
      setTimeout(() => {
        setItems(cols)
      }, 2000)
    }
  }, [cols]);

  return (
        <Container>
          <Row>
            {appear && transitions.map(({ item, props, key }) => (
              <Col className="feature-item">
                <animated.div key={key} style={props} >
                  {item.component}
                </animated.div>
              </Col>
            ))}
          </Row>
        </Container>
  );
}

I tried using appear && transitions.map(...) but unfortunately that doesn't work. Any idea how should I control the start of the animation based on a condition?

like image 358
John C. Avatar asked Oct 27 '25 10:10

John C.


1 Answers

I use https://github.com/civiccc/react-waypoint for this type of problems.

If you place this hidden component just before your animation. You can switch the appear state with it. Something like this:

<Waypoint
  onEnter={() => setAppear(true) }
/>

You can even specify an offset with it. To finetune the experience.

like image 156
Peter Ambruzs Avatar answered Oct 29 '25 23:10

Peter Ambruzs