React の useTitle フック

Beginner

This tutorial is from open-source community. Access the source code

はじめに

この実験では、React における useTitle フックを使って Web ページのタイトルを動的に設定する方法を学びます。このフックは、表示されるコンテンツに基づいてページタイトルを動的に変更する必要がある Web アプリケーションを構築する際に便利です。この実験を通じて、useTitle フックを実装し、実際の例で使う方法を探ります。

React useTitle フック

VM には既に index.htmlscript.js が用意されています。一般的には、script.jsstyle.css にのみコードを追加すればよいです。

ページのタイトルを設定するには、useTitle というカスタムフックを使用できます。このフックは、typeof を使って Document が定義されているかどうかを確認します。定義されている場合、useRef() フックを使って Document の元のタイトルを格納します。その後、useEffect() フックを使ってコンポーネントがマウントされたときに Document.title を渡された値に設定し、アンマウントされたときにクリーンアップします。

const useTitle = (title) => {
  const documentDefined = typeof document !== "undefined";
  const originalTitle = React.useRef(documentDefined ? document.title : null);

  React.useEffect(() => {
    if (!documentDefined) return;

    if (document.title !== title) {
      document.title = title;
    }

    return () => {
      document.title = originalTitle.current;
    };
  }, [title]);
};

サンプルコードでは、Alert コンポーネントが useTitle フックを使ってタイトルを "Alert" に設定しています。MyApp コンポーネントは、Alert コンポーネントを切り替えるボタンをレンダリングしています。

const Alert = () => {
  useTitle("Alert");

  return (
    <div>
      <p>Alert! Title has changed</p>
    </div>
  );
};

const MyApp = () => {
  const [alertOpen, setAlertOpen] = React.useState(false);

  return (
    <div>
      <button onClick={() => setAlertOpen(!alertOpen)}>Toggle alert</button>
      {alertOpen && <Alert />}
    </div>
  );
};

ReactDOM.render(<MyApp />, document.getElementById("root"));

右下隅の「Go Live」をクリックして、ポート 8080 で Web サービスを実行してください。その後、Web 8080 タブを更新して Web ページをプレビューできます。

まとめ

おめでとうございます!あなたは React useTitle フックの実験を完了しました。あなたの技術を向上させるために、LabEx でさらに多くの実験を行って練習してください。