React Router DOM の使用方法

WBOY
リリース: 2024-08-24 11:02:32
オリジナル
211 人が閲覧しました

How to use React Router DOM

導入

React Router DOM に関する詳細なチュートリアルへようこそ!動的ルーティング機能を使用して React アプリケーションを強化したいと考えている UI 開発者にとって、ここは適切な場所です。 React Router DOM は、スムーズでシームレスなユーザー エクスペリエンスを維持しながら、複数のビューを持つ単一ページ アプリケーションを作成できる強力なライブラリです。

この包括的なガイドでは、基本概念から高度なテクニックまで、React Router DOM について知っておくべきことをすべて説明します。 React の初心者でも、スキルのレベルアップを目指す経験豊富な開発者でも、このチュートリアルでは、React アプリケーションにルーティングを効果的に実装するために必要な知識と実践的な例を提供します。

それでは、一緒に React Router DOM の世界に飛び込んで探索しましょう!

React Router DOM を使ってみる

React Router DOM とは何ですか?

React Router DOM は、React アプリケーション用の人気のあるルーティング ライブラリです。これにより、シングルページ アプリケーション (SPA) で動的なクライアント側ルーティングを作成できます。 React Router DOM を使用すると、現在の URL に基づいてさまざまなビューやコンポーネントを簡単に管理でき、ユーザーにシームレスなナビゲーション エクスペリエンスを提供できます。

React Router DOM のインストール

React アプリケーションでルーティングの実装を開始する前に、React Router DOM パッケージをインストールする必要があります。ターミナルを開いてプロジェクト ディレクトリに移動し、次のコマンドを実行します:

npm install react-router-dom
ログイン後にコピー

これにより、最新バージョンの React Router DOM がプロジェクトにインストールされます。

基本的なセットアップ

アプリケーションで React Router DOM の使用を開始するには、必要なコンポーネントをインポートし、メインのアプリケーション コンポーネントを BrowserRouter コンポーネントでラップする必要があります。以下は、index.js ファイルで React Router DOM をセットアップする方法の基本的な例です:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);
ログイン後にコピー

基本的なセットアップが完了したので、React Router DOM のコア コンポーネントとそれらを効果的に使用する方法を見てみましょう。

React Router DOM のコアコンポーネント

ルートとルート

ルートとルートコンポーネントは、React Router DOM の構成要素です。これらを使用すると、アプリケーション内のルートごとにレンダリングする必要があるさまざまなパスとコンポーネントを定義できます。

これらのコンポーネントの使用方法の例を次に示します:

import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} />
      <Route path="/contact" element={<Contact />} />
    </Routes>
  );
}

export default App;
ログイン後にコピー

この例では、ホームページ ("/")、概要ページ ("/about")、および連絡先ページ ("/contact") の 3 つのルートを定義しました。各ルートは、対応する URL にアクセスしたときにレンダリングされる特定のコンポーネントに関連付けられています。

リンクコンポーネント

Link コンポーネントは、アプリケーション内にナビゲーション リンクを作成するために使用されます。これは、ユーザーがページ全体のリロードをトリガーせずに異なるビュー間を移動できるようにするため、React Router DOM の重要な部分です。

リンク コンポーネントの使用方法は次のとおりです:

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

function Navigation() {
  return (
    <nav>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/contact">Contact</Link></li>
      </ul>
    </nav>
  );
}

export default Navigation;
ログイン後にコピー

NavLink コンポーネント

NavLink コンポーネントは Link に似ていますが、アクティブなリンクをスタイル設定するための追加機能を提供します。これは、現在アクティブなページを強調表示するナビゲーション メニューを作成する場合に特に便利です。

NavLink の使用方法の例を次に示します:

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

function Navigation() {
  return (
    <nav>
      <ul>
        <li>
          <NavLink to="/" style={({ isActive }) => isActive ? { color: 'red' } : undefined}>
            Home
          </NavLink>
        </li>
        <li>
          <NavLink to="/about" style={({ isActive }) => isActive ? { color: 'red' } : undefined}>
            About
          </NavLink>
        </li>
        <li>
          <NavLink to="/contact" style={({ isActive }) => isActive ? { color: 'red' } : undefined}>
            Contact
          </NavLink>
        </li>
      </ul>
    </nav>
  );
}

export default Navigation;
ログイン後にコピー

この例では、isActive プロップを使用してアクティブなリンクに赤色を適用しています。

高度なルーティング技術

基本を説明したので、React Router DOM を使用して実装できるより高度なルーティング テクニックをいくつか見てみましょう。

ネストされたルート

ネストされたルートを使用すると、アプリケーション内でより複雑なルーティング構造を作成できます。これは、共有コンポーネントを含むレイアウトを作成したり、関連するルートを整理したりする場合に特に便利です。

ネストされたルートを実装する方法の例を次に示します。

import React from 'react';
import { Routes, Route, Outlet } from 'react-router-dom';
import Header from './components/Header';
import Footer from './components/Footer';
import Home from './components/Home';
import About from './components/About';
import Services from './components/Services';
import ServiceDetails from './components/ServiceDetails';

function Layout() {
  return (
    <div>
      <Header />
      <Outlet />
      <Footer />
    </div>
  );
}

function App() {
  return (
    <Routes>
      <Route path="/" element={<Layout />}>
        <Route index element={<Home />} />
        <Route path="about" element={<About />} />
        <Route path="services" element={<Services />} />
        <Route path="services/:id" element={<ServiceDetails />} />
      </Route>
    </Routes>
  );
}

export default App;
ログイン後にコピー

この例では、ヘッダーとフッターを含むレイアウト コンポーネントを作成しました。 Outlet コンポーネントは、レイアウト内の子ルートをレンダリングするために使用されます。

動的ルートと URL パラメータ

動的ルートを使用すると、可変セグメントを処理できる柔軟なパスを作成できます。これは、製品ページやユーザー プロフィールなど、特定のアイテムに関する詳細情報を表示する必要があるシナリオに役立ちます。

動的ルートを使用して URL パラメーターにアクセスする方法の例を次に示します。

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

function ProductDetails() {
  const { productId } = useParams();

  return (
    <div>
      <h1>Product Details</h1>
      <p>You are viewing product with ID: {productId}</p>
    </div>
  );
}

export default ProductDetails;
ログイン後にコピー

このコンポーネントを使用するには、次のようなルートを定義します:

<Route path="/products/:productId" element={<ProductDetails />} />
ログイン後にコピー

プログラムによるナビゲーション

場合によっては、特定の条件やユーザーのアクションに基づいてプログラムでナビゲートする必要があります。 React Router DOM は、この目的のために useNavigate フックを提供します。

Here's an example of how to use useNavigate:

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

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

  const handleSubmit = (event) => {
    event.preventDefault();
    // Perform login logic here
    // If login is successful, navigate to the dashboard
    navigate('/dashboard');
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields */}
      <button type="submit">Login</button>
    </form>
  );
}

export default LoginForm;
ログイン後にコピー

Handling Route Parameters and Query Strings

React Router DOM provides powerful tools for working with route parameters and query strings, allowing you to create dynamic and flexible routing solutions.

Route Parameters

We've already seen how to use route parameters with the useParams hook. Let's explore this further with a more complex example:

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

function BlogPost() {
  const { category, postId } = useParams();

  return (
    <div>
      <h1>Blog Post</h1>
      <p>Category: {category}</p>
      <p>Post ID: {postId}</p>
    </div>
  );
}

export default BlogPost;
ログイン後にコピー

To use this component, you would define a route like this:

<Route path="/blog/:category/:postId" element={<BlogPost />} />
ログイン後にコピー

This allows you to create URLs like /blog/technology/123 or /blog/travel/456, with the category and post ID being dynamically extracted from the URL.

Query Strings

Query strings are useful for passing optional parameters to your routes. React Router DOM provides the useSearchParams hook to work with query strings.

Here's an example of how to use useSearchParams:

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

function ProductList() {
  const [searchParams, setSearchParams] = useSearchParams();
  const category = searchParams.get('category');
  const sortBy = searchParams.get('sortBy');

  return (
    <div>
      <h1>Product List</h1>
      <p>Category: {category || 'All'}</p>
      <p>Sort By: {sortBy || 'Default'}</p>
      <button onClick={() => setSearchParams({ category: 'electronics', sortBy: 'price' })}>
        Filter Electronics, Sort by Price
      </button>
    </div>
  );
}

export default ProductList;
ログイン後にコピー

In this example, we're reading the category and sortBy parameters from the query string. We're also demonstrating how to update the query string using the setSearchParams function.

Protecting Routes and Handling Authentication

One common requirement in many applications is to protect certain routes based on user authentication status. React Router DOM can be used in conjunction with your authentication logic to create protected routes.

Here's an example of how you might implement protected routes:

import React from 'react';
import { Route, Navigate } from 'react-router-dom';

function ProtectedRoute({ element, isAuthenticated, ...rest }) {
  return (
    <Route
      {...rest}
      element={isAuthenticated ? element : <Navigate to="/login" replace />}
    />
  );
}

function App() {
  const [isAuthenticated, setIsAuthenticated] = React.useState(false);

  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/login" element={<Login setIsAuthenticated={setIsAuthenticated} />} />
      <ProtectedRoute
        path="/dashboard"
        element={<Dashboard />}
        isAuthenticated={isAuthenticated}
      />
    </Routes>
  );
}

export default App;
ログイン後にコピー

In this example, we've created a ProtectedRoute component that checks if the user is authenticated. If they are, it renders the specified element; if not, it redirects them to the login page.

Handling 404 Pages and Redirects

React Router DOM makes it easy to handle 404 (Not Found) pages and implement redirects when necessary.

404 Pages

To create a 404 page, you can use the * path at the end of your route definitions:

import React from 'react';
import { Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import NotFound from './components/NotFound';

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} />
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}

export default App;
ログイン後にコピー

In this example, the NotFound component will be rendered for any route that doesn't match the defined paths.

Redirects

Sometimes you may need to redirect users from one route to another. React Router DOM provides the Navigate component for this purpose:

import React from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import Home from './components/Home';
import OldPage from './components/OldPage';
import NewPage from './components/NewPage';

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/old-page" element={<Navigate to="/new-page" replace />} />
      <Route path="/new-page" element={<NewPage />} />
    </Routes>
  );
}

export default App;
ログイン後にコピー

In this example, any user trying to access /old-page will be automatically redirected to /new-page.

Optimizing Performance with Code Splitting

As your application grows, you may want to implement code splitting to improve performance. React Router DOM works well with React's lazy loading feature, allowing you to load route components only when they're needed.

Here's an example of how to implement code splitting with React Router DOM:

import React, { Suspense, lazy } from 'react';
import { Routes, Route } from 'react-router-dom';

const Home = lazy(() => import('./components/Home'));
const About = lazy(() => import('./components/About'));
const Contact = lazy(() => import('./components/Contact'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </Suspense>
  );
}

export default App;

In this example, we're using React's `lazy` function to dynamically import our components. The `Suspense` component is used to show a loading indicator while the component is being loaded.
ログイン後にコピー

Conclusion

Congratulations! You've now completed a comprehensive tutorial on React Router DOM. We've covered everything from basic setup to advanced techniques like nested routes, dynamic routing, authentication, and code splitting. With this knowledge, you're well-equipped to implement robust routing solutions in your React applications.

Remember, the key to mastering React Router DOM is practice. Try implementing these concepts in your own projects, and don't be afraid to experiment with different routing structures and techniques. As you become more comfortable with React Router DOM, you'll find that it opens up new possibilities for creating dynamic and user-friendly web applications.

以上がReact Router DOM の使用方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!