First, we need to install the framer-motion library. You can do this by running the following command:
Next, we are going to create a page to showcase the component.
Let's make a file called ìndex.js and add the following code:
And let's add some styles for the page. Create a file called styles.css and add the following code:
The TextLoop component
Now, let's create a new file called TextLoop.js and add the following code:
That's a lot of code so let's break it down:
We define the variants object that will be used to animate the text.
We create the TextLoop component that receives an array of words and a className as props.
We added a state variable index to keep track of the current word to show.
We use the useEffect hook to update the index every 3 seconds.
We use the AnimatePresence component to fade out the text when it is removed from the DOM.
Using the TextLoop component
Go back to the ìndex.js file and add the following code:
What we did is create a new Word component to handle the styles of the sliding text. Then we created an array of "words" and passed it to the TextLoop component along with a className for styling the container.
Now let's add those styles to the styles.css file:
And that's it! You should now see the text loop animation in action.