LoginSignup
3
1

React Routerとhistory【初心者向け解説】

Posted at

Webアプリケーションを作成する際、異なるページ間を移動する機能は必須です。React Routerは、Reactで使うことができるルーティングライブラリで、このようなページ遷移を管理します。

今回は、React Routerの重要な部分であるhistoryオブジェクトについて解説します。

React Routerとは何か

React Routerは、シングルページアプリケーション(SPA)でページ間の遷移を可能にするためのライブラリです。SPAでは、通常、ページ全体をリロードせずに部分的な更新(通常はコンポーネントの置換)を行うことで、ユーザーに複数ページが存在するかのように感じさせます。

historyとは何か

historyはReact Routerが提供するオブジェクトで、ブラウザの履歴スタックの状態を管理します。historyオブジェクトは、ページ遷移を行ったり、前のページに戻ったりするためのメソッドを提供します。

history.push('/home'); //新しいエントリを履歴スタックに追加し、その位置に遷移します。
history.replace('/home'); //現在のエントリを新しいもので置き換え、その位置に遷移します。
history.goBack(); //履歴スタックの前のエントリに遷移します。
history.goForward(); //履歴スタックの次のエントリに遷移します。

historyの利用方法

React Router v5までは、withRouter 高階コンポーネント(HOC)を使用してhistoryオブジェクトにアクセスすることができました。しかし、React Router v6ではこの方法は廃止され、代わりにuseHistory フックを使用します。

例: React Router v5

import React from 'react';
import { withRouter } from 'react-router-dom';

function MyComponent({ history }) {
  const navigateToHome = () => {
    history.push('/home');
  };

  return (
    <button onClick={navigateToHome}>
      Go to Home
    </button>
  );
}

export default withRouter(MyComponent);

例: React Router v6

import React from 'react';
import { useNavigate } from 'react-router-dom';

function MyComponent() {
  const navigate = useNavigate();

  const navigateToHome = () => {
    navigate('/home');
  };

  return (
    <button onClick={navigateToHome}>
      Go to Home
    </button>
  );
}

export default MyComponent;

まとめ

React Routerのhistoryオブジェクトは、ブラウザの履歴スタックを管理し、ページ間の遷移を制御する強力なツールです。ページ遷移を行うpushメソッドや前のページに戻るgoBackメソッドなど、様々なメソッドを提供しています。

React Router v5では、withRouter 高階コンポーネントを用いてhistoryオブジェクトにアクセスできましたが、React Router v6ではこの方法が廃止され、代わりにuseNavigateフックを使用します。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1