Alex Reed
Alex Reed

Reputation: 1

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

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"/>

Upvotes: 0

Views: 2161

Answers (1)

Joshua Wootonn
Joshua Wootonn

Reputation: 1276

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

Upvotes: 0

Related Questions