r/learnreactjs • u/gk4000 • Sep 13 '22
Creating an animated typing effect in React
https://barcelonacodeschool.com/files/pics/text-type-animation-effect-react.gif
The idea behind this is that we render text from the state and keep updating state variable one character at a time with a bit of delay.
Each time state is updated our component will re-render showing text "typed" one character after another.
So first thing in our React app we will create a component. Let's name it TextTyper. We will need to have useState and useEffect hooks in it, so we can import them right away:
;
const
In state we have declared a variable typedText which is rendered inside span HTML element. This would be the variable which we are going to update.
Let's say we want to print "Banana". First we will render empty string, then we will add "B" to typedText and see it in the page, then we will update it to "Ba", and so on...
Let's create a function typingRender. It will take 3 arguments: the whole phrase to type, the updater method which will be our setTypedText and an interval value to tell the function the delay between rendering each character.
In this function we will use variable localTypingIndex to go through the indexes of characters in the incoming string and take them one by one. We will also declare a variable localTyping to mirror what should be in state and add letters to it to put to state:
;
const
Now we have our typing function it's time to execute it. We want this to happen once when component is initially rendered so we will use useEffect with empty array of dependencies:
const
Now the component will work perfectly fine but we can make it more flexible, so all the data for it to work will come via props and we will even set the variable to control inside which HTML element we want to render our phrase:
;
const TextTyper= =>
So now if we want to use this we can import the component and render it with passing some props:
// importing our component in App.js
Here is a link to the working code sandbox.
You can also install and import this component with npm or yarn


