Using typed.js with React function components

593 views Asked by At

typed.js doesn't offer an example for this in the docs, only for class components:

class TypedReactDemo extends React.Component {
  componentDidMount() {
    const options = { ... };
    this.typed = new Typed(this.el, options );
  }

  render() {
    return (
      <span ref={(el) => { this.el = el; }} />
    );
  }
}
1

There are 1 answers

0
thisismydesign On BEST ANSWER
import React, { useRef, useEffect } from "react";
import Typed from "typed.js";

const Example = () => {
  const typeTarget = useRef(null);

  useEffect(() => {
    const typed = new Typed(typeTarget.current, {
      strings: ["<i>First</i> sentence.", "&amp; a second sentence."],
      typeSpeed: 40,
    });

    return () => {
      typed.destroy();
    };
  }, []);

  return <span ref={typeTarget} />;
};

export default Example;