【React】タイピングアニメーションのreact-typicalをReactv17, v18以上で使いたいとき

2023年10月18日React

Reactで簡単にタイピングアニメーションを実装できるreact-typicalの使い方を紹介します。
reactのバージョンが15か16しか対応していませんが、v17, v18以上で使う方法はあるので合わせて紹介します。
あとは更新されていないものを無理に使う必要もないので、代替のライブラリや自作するコードサンプル例も合わせて紹介します。

タイピングアニメーションのreact-typicalをReact v17, v18以上で使う方法

公式サイト: https://www.npmjs.com/package/react-typical
まず、公式のnpmコマンドでインストールできないか試します。

npm install --save react-typical

インストールが完了すれば問題なしです。
ただ、

npm ERR! ERESOLVE unable to resolve dependency tree

といったメッセージが出現した場合、インストールできていません。
なので、強制的にインストールする方法があります。

npm install react-typical --force

こちらのコマンドでインストールできるはずです。

インポートして使用

import React from "react";
import Typical from "react-typical";

export default function Sample() {
  return (
         <h1>
          <Typical
              loop={Infinity}
              steps={[
                "文章1文章1文章1文章1",
                  1000,
                  "文章2文章2文章2文章2",
                  1000,
                  "文章3文章3文章3文章3",
                  1000,
                ]}
              />
           </h1>
  );
}

あとは、react-typicalをインポートします。
loopをしたい場合は、loop属性にInfinityをセットします。
stepsの中に配列を用意して、あとはタイピングして表示したい文章をいれていくだけです。

代替ライブラリ:React Simple Typewriter

公式サイト: https://www.npmjs.com/package/react-simple-typewriter

React Simple Typewriterは、シンプルで使いやすいタイプライターエフェクトを提供します。

インストール


npm install react-simple-typewriter

使用例

import React from 'react';
import { Typewriter } from 'react-simple-typewriter';

export default function App() {
  return (
    <h1>
      <Typewriter
        words={['文章1文章1文章1文章1', '文章2文章2文章2文章2', '文章3文章3文章3文章3']}
        loop={0} // 0の場合、無限ループ
        cursor
        cursorStyle='_'
        typeSpeed={70}
        deleteSpeed={50}
        delaySpeed={1000}
      />
    </h1>
  );
}

代替ライブラリ:React Type Animation

公式サイト: https://www.npmjs.com/package/react-type-animation

React Type Animationカスタマイズ可能なタイピングアニメーションコンポーネントを提供します。

インストール


npm install react-type-animation

使用例

import React from 'react';
import { TypeAnimation } from 'react-type-animation';

export default function App() {
  return (
    <h1>
      <TypeAnimation
        sequence={[
          '文章1文章1文章1文章1',
          1000, // 1秒間の待機
          '文章2文章2文章2文章2',
          1000,
          '文章3文章3文章3文章3',
          1000,
        ]}
        wrapper="span"
        cursor={true}
        repeat={Infinity}
        style={{ display: 'inline-block' }}
      />
    </h1>
  );
}

タイピングアニメーションを自作する場合の例

外部ライブラリを使用せずにタイピングアニメーションを実装することも可能です。

import React, { useState, useEffect } from 'react';

export default function App() {
  const messages = ['文章1文章1文章1文章1', '文章2文章2文章2文章2', '文章3文章3文章3文章3'];
  const [currentMessage, setCurrentMessage] = useState('');
  const [messageIndex, setMessageIndex] = useState(0);
  const [charIndex, setCharIndex] = useState(0);
  const [isDeleting, setIsDeleting] = useState(false);
  const [speed, setSpeed] = useState(150);

  useEffect(() => {
    const handleTyping = () => {
      const currentFullMessage = messages[messageIndex];
      setCurrentMessage(
        isDeleting
          ? currentFullMessage.substring(0, charIndex - 1)
          : currentFullMessage.substring(0, charIndex + 1)
      );

      setCharIndex((prev) => (isDeleting ? prev - 1 : prev + 1));

      if (!isDeleting && charIndex === currentFullMessage.length) {
        setTimeout(() => setIsDeleting(true), 1000);
      } else if (isDeleting && charIndex === 0) {
        setIsDeleting(false);
        setMessageIndex((prev) => (prev + 1) % messages.length);
      }

      setSpeed(isDeleting ? 30 : 150);
    };

    const timer = setTimeout(handleTyping, speed);
    return () => clearTimeout(timer);
  }, [charIndex, isDeleting, messageIndex, messages, speed]);

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

このコードでは、useStateとuseEffectを使用して、文字列を一文字ずつ表示・削除するアニメーションを実現しています。

React

Posted by devsakaso