Trigger animation in react-spring on condition

Viewed 420

how do I trigger an animation on a condition. For example I want to fade in a component only when the user scrolled to the part of the page. If I would just do a normal useSpring() the animation would trigger right away even if it is at the bottom of the whole page and the user wouldn't even see it.

2 Answers

I am playing around with react-spring and was thinking about the same, but it's late and I have no better solution yet as to choose the same styles when the condition fails, like this:

  const fadeIn = useSpring({
    to: {
      opacity: isDesiredScrollPosition ? 1 : 0
    },
    from: {
      opacity: 0
    }
  });

Consider using the imperative API for better control of when your animations run.

To answer your question specifically, I would use an intersection observer to run api.start when there's a successfull intersection. It could look something like this:

const FadeUp = ({ children }) => {
  const ref = useRef(null)
  const [styles, api] = useSpring(() => ({
    from: {
      y: 100,
      opacity: 0,
    }
  }))

  useEffect(() => {
    const entry = ref.current
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        api.start({
          to: {
            y: 0,
            opacity: 1,
          },
        })

        observer.unobserve(entry)
      }
    })
    observer.observe(entry)
    return () => observer.unobserve(entry)
  }, [])

  return (
    <FadeInComp ref={ref} style={styles}>
      {children}
    </FadeInComp>
  )
}
Related