How to create moving image from right to left with reverse using react-spring?

1.8k Views Asked by At

Can someone help me with my propblem? I need to make animation with png image on my react project. My img must moving from right to left in own block with reverse in the end of the right side and left side. I made a part of my code, but cann't understand how to make reverse? I use react-spring. const [key, setKey] = useState(1);

const styles = useSpring({
    from: { transform: "translate(50%,0)" },
    to: { transform: "translate(-50%,0)" },
    config: { duration: 4000 },
    reset: true,
    reverse: key % 2 == 0,
    onRest: () => {
        setKey(key + 1);
      }
})

return <animated.img img className={classes.fishPicture} style={styles} src={fishOne} alt="fish"/>

1

There are 1 best solutions below

5
On

You can use an array version of the to key take the animation back to the original location and then combine that with loop: true

  const styles = useSpring({
    from: { transform: "translate(50%,0)" },
    to: [{ transform: "translate(-50%,0)" }, { transform: "translate(50%,0)" }],
    config: { duration: 500 },
    loop: true
  });

Here is a working example I created: https://codesandbox.io/s/react-spring-looping-tranform-animation-tgb7z