DEV Community

Cover image for How to use Typed.js in React (Beginner friendly)
Kristine Gusta
Kristine Gusta

Posted on

How to use Typed.js in React (Beginner friendly)

React nowadays is a popular, powerful and very in demand library for Web Development .

However, for a React beginner like me ,sometimes it is troublesome to implement in my React projects the libraries that I used to use in Vanilla JS.

That is why I would like to share some simple JS packages that you can also use with React to make your Website a little bit more fun and appealing, and perhaps make you less afraid of React. Today I will share one.

Typed.js

Ever saw a website with a subtitle with a nice typing-like effect? Typed.js is a way how to implement this easy and fast.

Here is an example

Installation

npm install typed.js
yarn add typed.js
bower install typed.js
Enter fullscreen mode Exit fullscreen mode

Set up

Like all the packages, import it in the top of your page.

import Typed from "typed.js";

To make this package work in React, we need to use 2 React hooks - one for referencing (or selecting) the element where we want our Typed strings to go, and the other one to perform side effects, in this scenario, it would be manipulating the DOM. Those are useRef and *useEffect

import { useEffect, useRef } from "react";

In this example, I would like my Typed items to finish the heading, therefore, I reference the tag using the useRef hook.

const TypedTitle = () => {
  const el = useRef(null);
  return (
    <h1>
      I am <span ref={el}></span>{" "}
    </h1>
  );
};
Enter fullscreen mode Exit fullscreen mode

Initialize Typed.js

Now, all you need to do is add a UseEffect hook where the Callback will be our Typed initialization.

const TypedTitle = () => {
  const el = useRef(null);
  useEffect(() => {
    const typed = new Typed(el.current, {
      strings: [
        "Full stack developer",
        "Front-end developer",
        "React Developer",
      ],
      startDelay: 300,
      typeSpeed: 100,
      backSpeed: 100,
      backDelay: 100,
      loop: true,
    });

    // Destroying
    return () => {
      typed.destroy();
    };
  }, []);
  return (
    <h1>
      I am <span ref={el}></span>{" "}
    </h1>
  );
};
Enter fullscreen mode Exit fullscreen mode

The array of strings are the Typed items you would like to appear and disappear . Of course you can customize the animation by adjusting the object values.

And now you are good to go!

Credit to the original creator Matt Bold.

Link to GitHub

Top comments (0)