React - typing effect with useEffect()

0 votes
112 views
added Feb 1 in React by lcjr First Warrant Officer (11,990 points)
import React, { useState, useEffect } from 'react';
import { css, jsx } from '@emotion/react';

const BuddySearchText = () => {
  const [text, setText] = useState('');
  const dummyText = `
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
    quis nunc dui. Maecenas cursus, ex a bibendum tristique, lacus sem
    luctus arcu, at mattis augue metus sed ante. Curabitur sit amet
    consequat elit. Donec eget maximus metus. Donec eu felis nec lorem
    ultricies mollis non nec ante. Cras eu rutrum mi, in pellentesque neque.
    Phasellus ullamcorper, nisi sit amet egestas dictum, eros velit tempus
    dolor, eget cursus tellus neque vehicula magna. Orci varius natoque
    penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam
    tristique nunc nulla, ut congue eros hendrerit eu. Quisque sit amet 
  `;

  useEffect(() => {
    let index = 0;

    const intervalId = setInterval(() => {
      setText(dummyText.slice(0, index));
      index += 1;

      if (index > dummyText.length) {
        clearInterval(intervalId);
      }
    }, 50);

    return () => clearInterval(intervalId);
  }, []);

  return (
    <>
      <p>{text}</p>
    </>
  );
};

export default BuddySearchText;

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...