5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

react-router-domを簡単に解釈する

Last updated at Posted at 2024-02-23

react-router-domとは

react-router-domは、React用のサードパーティ製ルーティングライブラリで、シングルページアプリケーション(SPA)のページ遷移をページのリロードなしに実現できる便利なツールです。
また、ウェブアプリケーション専用に設計されたreact-routerの拡張版であり、ブラウザベースの環境に最適化された追加機能を備えています。
react-router-domをインストールすることで、react-router のコア機能に加えて、ウェブ特有の機能(例えば、<Link><BrowserRouter> など)を利用できます。

この記事は、React Router v6を前提にしております。

react-router-domのセットアップ

パッケージのインストール

まず、プロジェクトに react-router-dom ライブラリをインストールします。プロジェクトのルートディレクトリで以下のコマンドを実行してください。

npm install react-router-dom

TypeScriptなら以下のようになります。

npm install react-router-dom @types/react-router-dom

このコマンドは、react-router-dom およびその依存関係をプロジェクトに追加します。

実装例

ルーティングの設定

次に、アプリケーションのルーティングを設定します。react-router-dom から BrowserRouterRoutesRouteLink コンポーネントをインポートし、アプリケーションの異なる部分へのルーティングを定義します。

ディレクトリ構成は以下になります。

ディレクトリ構成
my-app/
├── public/
│   └── index.html
├── src/
│   ├── components/        # 再利用可能なUIコンポーネント
│   │   └── navBar.tsx      # ナビゲーションバー コンポーネント
│   ├── pages/             # 各ページを表すコンポーネント
│   │   ├── home.tsx        # Home ページ コンポーネント
│   │   └── about.tsx       # About ページ コンポーネント
│   ├── App.tsx             # アプリケーションのルートコンポーネント
│   └── main.tsx           # アプリケーションのエントリーポイント
└── package.json           # プロジェクトのメタデータと依存関係

そして、以下は、基本的なルーティングの設定例です。

main.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App.tsx";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);
App.tsx
import { Routes, Route } from 'react-router-dom';
import { NavBar } from './NavBar';
import { Home } from './Home';
import { About } from './About';

const App = () => {
  return (
    <Routes>
      <NavBar /> {/* ナビゲーションバーを挿入 */}
      {/* ルート定義 */}
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} /> 
      {/*
      react-router-dom v6以前では、Componentが使われていた
      <Route path="/"  Component={Home} />
      <Route path="/about" Component={About} />
      */}
    </Routes>
  );
};

export default App;
navBar.tsx
import {FunctionComponent} from 'react';
import { Link } from 'react-router-dom';

const NavBar: FunctionComponent = () => {
  return (
    <nav>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
      </ul>
    </nav>
  );
};

export default NavBar;
home.tsx
import {FunctionComponent} from 'react';

const Home: FunctionComponent = () => {
  return <h2>Home</h2>;
};

export default Home;
about.tsx
import {FunctionComponent} from 'react';

const About: FunctionComponent = () => {
  return <h2>About</h2>;
};

export default About;

このコード例では、react-router-dom を使用して、ユーザーがブラウザのURLバーを通じてアクセスする各ページ(「Home」と「About」)へのルーティングを実装しています。

ユーザーが「/」のURLにアクセスすると「Home」ページが、そして「/about」のURLにアクセスすると「About」ページが表示されます。

実装が完了したら、アプリケーションを起動して、ルーティングが正しく機能していることを確認します。

npm start

コード解説

<BrowserRouter> コンポーネント

<BrowserRouter>Router としてインポート)は、HTML5のhistory APIを利用してUIとURLの同期を行います。

<Link> コンポーネント

<Link> コンポーネントは、アプリケーション内でのナビゲーションリンクを作成し、ページリロードを発生させずにビューを切り替えることができます。

v6から廃止されたもの

exact プロパティ

v6からはexactはデフォルトで全文一致で探してくれるようなので廃止されているようです。

参考

5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?