Search code examples
reactjsreact-nativereact-spring

How to change colors using React-Spring. I would like to include delay and duration


I am using react-spring. I am changing the background color which is working however I am hoping to do the following. Wait for 10 seconds then after those 10 seconds loop through the colors without the delay. I would also like to have a 1 second duration of each color.

currently my issue is that it waits 10 seconds then it starts to loop but makes me wait 10 seconds between every color change. Not sure what I am doing wrong

  import {useSpring, animated} from 'react-spring';

  const AnimatedView = animated(View);

  const bgStyle = useSpring({
    to: {backgroundColor: 'red'},
    from: {backgroundColor: 'green'},
    delay: 10000,
    config: {duration: 1000},
    loop: true,
  });

  return <AnimatedView style={bgStyle}>{props.children}</AnimatedView>;

Solution

  • I think we need to wait for 10s once at first. But the delay prop of useSpring makes us wait for 10s at the start of each animation. Because the value of delay is not updating, it is always 10000.

    Here we can take a useRef reference to track our initial delay. By checking this we can return a delay of 10000 at first and then 0 for the rest.

      const initialDelay = useRef(true);
    
      const bgStyle = useSpring({
        from: { backgroundColor: "green" },
        to: { backgroundColor: "red" },
        delay: () => {
          if (initialDelay.current) {
            initialDelay.current = false;
            return 10000;
          }
          return 0;
        },
        config: { duration: 1000 },
        loop: true
      });
    

    Edit react-spring-delay-duration