React.js ライブラリ「react-simple-typewriter」を使って見栄えのいいタイプライターを使用する

React.js ライブラリ「react-simple-typewriter」を使って見栄えのいいタイプライターを使用する

ライブラリ「react-simple-typewriter」をインストールすると、見栄えのいいタイプライターを使用することが可能です。ここでは、react.jsで「react-simple-typewriter」を利用するための手順と簡単な使い方を記述してます。

環境

  • OS  CentOS Stream release 8
  • node V14.15.1
  • npm 6.14.8
  • React 16.13.0

react.js環境構築

下記のコマンドで構築してます。ここでは、react-appという名前でプロジェクトを作成してます。

create-react-app react-app

react-simple-typewriterインストール

作成したプロジェクトに移動して、インストールします。

## 作成したプロジェクトに移動
cd react-app
 
## インストール
npm i react-simple-typewriter

react-simple-typewriter使い方

srcディレクトリにsample.jsと名前で下記のコードを記述します。

import React from 'react'
import Typewriter from 'react-simple-typewriter'
import 'react-simple-typewriter/dist/index.css'

const Sample = () => {

  return (
    <div>
      <h1
        style={{ paddingTop: '5rem', margin: 'auto 0', fontWeight: 'normal' }}
      >
        Life is simple{' '}
        <span style={{ color: 'red', fontWeight: 'bold' }}>
          {/* Style will be inherited from the parent element */}
          <Typewriter
            loop
            cursor
            cursorStyle='_'
            typeSpeed={70}
            deleteSpeed={50}
            delaySpeed={1000}
            words={['Eat', 'Sleep', 'Code', 'Repeat!']}
            onLoop={(loopCount) =>
              console.log(`Just completed loop ${loopCount}`)
            }
          />
        </span>
      </h1>
    </div>
  );
};

export default Sample;

次に、srcディレクトリ配下にあるApp.jsを下記のように編集します。

import React from 'react';
import Sample from './sample';
import './App.css';

function App() {
  const style = {
    width: "50%",
    margin: "0 auto",
    marginTop: 150,
  };
  return (
    <div className="App">
      <div style={style}>
        <Sample />
      </div>
    </div>
  );
}

export default App;

実行します。

npm start

ブラウザから http://プライベートIP:3000にアクセスすると、タイプライターが実装されていることが確認できます。