K
K
Kirill Ivanov2020-04-20 17:02:59
JavaScript
Kirill Ivanov, 2020-04-20 17:02:59

How to animate the appearance of text by letter in React?

Hello! Tell me, pliz, how to make the animation of the output of the text letter by letter, as if someone is typing it on the screen. Until some nonsense turns out5e9dab7660942492426094.jpeg

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rjyk, 2020-04-20
@pashkevich-d

let text = 'qwertyu';
let output = '';
let currentIndex = 0;

let intervalID = setInterval(() => {
    output += text[currentIndex];
    currentIndex += 1;
    console.log(output);
    if (currentIndex === text.length) {
        clearInterval(intervalID)
    };
}, 1000)

It is also recommended to do this through the useEffect hook:
function RenderSubtitle() {
  const [subtitle, setSubtitle] = useState('');
  const text = 'qwertyu';
  let currentIndex = 0;

  useEffect(() => {
    const id = setInterval(() => {
      setSubtitle(prev => prev + text[currentIndex] );
      currentIndex += 1;
      if (currentIndex === text.length) {
          clearInterval(id)
      };
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return <h1>{subtitle}</h1>;
}

A
alalala, 2020-04-20
@alalala

typed.js not?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question