Text Typing Effect using React Functional Component

Ayush Gupta
2 min readOct 15, 2020

Welcome folks ! Do you want to create typing effect on your webpage and you are using react. Believe me its a simple task to achieve you just need to have knowledge of functional components and two of the most common react hooks those are useState() and useEffect. If you thinking how we are going to use those then hold on we are going to discuss the same by step by step procedure in this post.

If you want to check out what we trying to achieve just go to link below.

https://codesandbox.io/s/flamboyant-maxwell-h8o4j?file=/src/App.js

Steps to create the typing effect :

  1. Create a function named TypingEffect this function will accept a prop named “text” which we will pass as string via props wherever we want to use this component in our app.
  2. The string “text” which is passed via props will used to as the content for the typing effect.
  3. Now create the state named “ typing” using useState hook and set it to blank string initially. We will be displaying this state on screen through <p> tag and this state will keep updating and will create the effect of typing on the screen. Now the point comes how we going to change this state.
  4. Also, create a another state named “index” and set it to initially 0. This will be used to keep track of the already typed text on the screen.
  5. Here the role of useEffect comes in, we will be using useEffect for changing the states “typing” and “index” thus invoking the rendering of the component again and thus changing the content of <p> tag as the state is changed.
  6. Inside useEffect simply check whether the length of index is less than the text needed to be typed as effect.

All set we are done just simply import this function anywhere in your react app and pass down the text props and enjoy getting people impressed by the cool effect of typing on our web page.

export default function TypingEffect(props) {
const [typing,setTyping] = useState('');const [index,setIndex] = useState(0);
useEffect(()=>{ if(index<props.text.length){ setTimeout(()=>{ setTyping(typing+props.text[index]); setIndex(index+1); },8); }},[index])
return
(
<div> <p>{typing}</p> </div> )
}

Watch live demo at https://codesandbox.io/s/flamboyant-maxwell-h8o4j?file=/src/App.js

--

--

Ayush Gupta
0 Followers

Web Developer 🌐 | Tech enthusiast | Passionate Prgogrammer 💻