Search code examples
reactjsreact-spring

How to create moving text from right to left using react-spring?


Moving text animation using react-spring?

I am developing a website using reactjs as front end, In header i want to move some text from right to left automatically,but i want to animate that with only react-spring! can anyone solve my problem?

Since i am new to react-spring,i can't find correct solution for this one!


Solution

  • React-spring is physic based and this type of animation is not really its strength. I would do something like this.

    import React, { useState } from "react";
    import { useSpring, animated } from "react-spring";
    
    const TextScroller = ({ text }) => {
      const [key, setKey] = useState(1);
    
      const scrolling = useSpring({
        from: { transform: "translate(60%,0)" },
        to: { transform: "translate(-60%,0)" },
        config: { duration: 2000 },
        reset: true,
        //reverse: key % 2 == 0,
        onRest: () => {
          setKey(key + 1);
        }
      });
    
      return (
        <div key={key}>
          <animated.div style={scrolling}>{text}</animated.div>);
        </div>
      );
    };
    
    export default TextScroller;
    

    It has room for improvement. Text length is not handled. Scrollbar can be disabled. But I leave something to you. :)

    working demo: https://codesandbox.io/s/basic-text-scroller-with-react-spring-siszy