How to make an effect typewriter

ajidk16

ajidk

Posted on February 10, 2023

How to make an effect typewriter

When I first opened chatgpt, I was interested in seeing typewriters, and then I became curious about typewriters and searched for various sources. Using Javascript, I try to implement this. and then

What is typewriter

A typewriter is a mechanical device that is used to type text on a screen. Several keypad buttons have letters, numbers, and symbols on their surfaces, which are pressed to write characters on a screen that moves beneath the rollers.

Typewriters: why use them

By making visitors focus on a single character for a designated period of time, this effect can enhance user engagement with web content and the page.

Example

Image description

code

Here's an example of how you can create a typewriter effect in React:

  1. Create a state to store the current text to be displayed on the screen:
  const [displayedContent, setDisplayedContent] = useState("");
  const [index, setIndex] = useState(0);
Enter fullscreen mode Exit fullscreen mode
  1. Create an variable content & speed to store the texts that you want to display one by one:
  let content = 'please visit suraji.my.id'
  let speed = 100
Enter fullscreen mode Exit fullscreen mode
  1. Use the useEffect hook to handle the animation:
  useEffect(() => {
    const animKey = setInterval(() => {
      setIndex((index) => {
        if (index >= content.length - 1) {
          clearInterval(animKey);
          return index;
        }
        return index + 1;
      });
    }, speed);
  }, [content.length, speed]);

  useEffect(() => {
    setDisplayedContent(
      (displayedContent) => displayedContent + content[index]
    );
  }, [content, index]);
Enter fullscreen mode Exit fullscreen mode
  1. Use the state in your component's render method to display the current text:
return <div>{displayedContent}</div>;
Enter fullscreen mode Exit fullscreen mode

This code will display the texts one by one with a typing effect, with a delay of 100ms pause between each text. You can adjust the delay and pause times to suit your needs.

Conclusion

By making visitors focus on a single character for a designated period of time, this effect can enhance user engagement with web content and the page.

💖 💪 🙅 🚩
ajidk16
ajidk

Posted on February 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Thất nghiệp tuổi 35
careerdevelopment Thất nghiệp tuổi 35

November 13, 2024

Understanding useMemo
react Understanding useMemo

October 18, 2024

"Coding is Magic!" ✨💻
javascript "Coding is Magic!" ✨💻

October 20, 2024

React js Features
react React js Features

October 16, 2024