Home >Web Front-end >JS Tutorial >React Router v6: A Beginner's Guide

React Router v6: A Beginner's Guide

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-02-08 11:33:11534browse

React Router v6: A Beginner's Guide

This tutorial provides a comprehensive guide to React Router v6, the leading routing library for React applications. Learn how to efficiently manage URLs and navigation within your React projects.

Key Learning Points:

  • Mastering React Router v6: This guide covers the fundamentals of setting up and using React Router v6 for seamless navigation and URL management in your React applications.
  • Route Navigation and Rendering: Discover how to create dynamic and nested routes using core components like <routes></routes>, <route></route>, and <link>, including the use of path parameters for flexible routing.
  • Advanced Routing Techniques: Explore advanced concepts such as protected routes, programmatic navigation with useNavigate, and the latest enhancements in React Router v6.4, enabling you to build sophisticated routing solutions for modern React applications.

Introduction:

React excels at building dynamic web applications with multiple views (pages). Unlike traditional multi-page apps, navigation shouldn't reload the entire page. Instead, views should render smoothly within the existing page. React Router achieves this declaratively, ensuring a seamless user experience. Users expect:

  • Unique URLs for Each View: Allowing bookmarking (e.g., www.example.com/products).
  • Functional Back/Forward Buttons: Standard browser navigation should work as expected.
  • URLs for Nested Views: Supporting dynamic, nested structures (e.g., example.com/products/shoes/101).

React Router's declarative approach simplifies routing by specifying the desired route structure:

<code class="language-jsx"><route path="/about" element="{<About"></route>} /></code>

<route></route> components can be placed anywhere within your application's structure. The simplicity of components like <route></route>, <link>, and other React Router APIs makes routing easy to implement.

Important Note: React Router is a third-party library maintained by Remix Software, not an official Facebook/Meta product.

Overview:

This tutorial covers:

  1. Setting up React and React Router using npm.
  2. Basic routing concepts.
  3. Nested routing.
  4. Dynamic nested routing with path parameters.
  5. Implementing protected routes.

The complete project code is available on GitHub (link to be inserted here).

Setting up React Router:

You'll need Node.js installed. If not, download it from the official Node.js website. Consider using a version manager for easier Node.js management. npm (Node Package Manager) is bundled with Node.js. Verify installation:

<code class="language-jsx"><route path="/about" element="{<About"></route>} /></code>

Create a new React project using Create React App:

<code class="language-bash">node -v
npm -v</code>

Install React Router DOM:

<code class="language-bash">npx create-react-app react-router-demo
cd react-router-demo</code>

Start the development server:

<code class="language-bash">npm install react-router-dom</code>

Your React app with React Router is now running at http://localhost:3000/.

React Router Basics:

We'll create an app with three views: Home, Categories, and Products.

The Router Component

Wrap your main app component with a router: BrowserRouter or HashRouter. BrowserRouter (using the HTML5 History API) is generally preferred for cleaner URLs:

<code class="language-bash">npm start</code>

History Object

Each router creates a history object managing the navigation stack. Changes to the location trigger re-rendering. useNavigate (hook) provides a navigate function for programmatic navigation.

Link and Route Components

<route></route> renders UI if the location matches the path. <link> provides navigation without page reloads.

Update App.js:

<code class="language-jsx">// src/index.js
import { BrowserRouter } from 'react-router-dom';
// ...
root.render(
  <react.strictmode>
    <browserrouter>
      <app></app>
    </browserrouter>
  </react.strictmode>
);</code>

This sets up basic navigation and routing.

Nested Routing:

Nest routes by placing <route></route> components within other <route></route> components. This mirrors the nested URL structure.

Modify App.js:

<code class="language-jsx">import { Link, Route, Routes } from 'react-router-dom';
// ... component definitions for Home, Categories, Products ...
export default function App() {
  return (
    <div>
      <nav>
        <ul>
          <li>
<link to="/">Home</li>
          <li>
<link to="/categories">Categories</li>
          <li>
<link to="/products">Products</li>
        </ul>
      </nav>
      <routes>
        <route path="/" element="{<Home"></route>} />
        <route path="/categories" element="{<Categories"></route>} />
        <route path="/products" element="{<Products"></route>} />
      </routes>
    </div>
  );
}</code>

Create Categories.js:

<code class="language-jsx">import { Link, Route, Routes } from 'react-router-dom';
import { Categories, Desktops, Laptops } from './Categories'; // Import nested route components

// ... other components ...

export default function App() {
  return (
    <div>
      {/* ... navigation ... */}
      <routes>
        <route path="/" element="{<Home"></route>} />
        <route path="/categories" element="{<Categories"></route>}>
          <route path="desktops" element="{<Desktops"></route>} />
          <route path="laptops" element="{<Laptops"></route>} />
        
        <route path="/products/*" element="{<Products"></route>} /> {/* Note the trailing * */}
      </routes>
    </div>
  );
}</code>

The <outlet></outlet> component renders child routes within the parent route.

Dynamic Nested Routing:

Use path parameters to create dynamic routes. Add a trailing * to the parent route to allow for child routes. Use useParams to access parameters.

Update Products.js:

<code class="language-jsx">import { Link, Outlet } from 'react-router-dom';

export const Categories = () => (
  <div>
    <h2>Categories</h2>
    <nav>
      <ul>
        <li>
<link to="desktops">Desktops</li>
        <li>
<link to="laptops">Laptops</li>
      </ul>
    </nav>
    <outlet></outlet>
  </div>
);

export const Desktops = () => <h3>Desktop PC Page</h3>;
export const Laptops = () => <h3>Laptops Page</h3>;</code>

The :productId parameter is accessed in the Product component using useParams.

Protecting Routes:

Use useNavigate for programmatic redirection and create a custom PrivateRoute component.

Create PrivateRoute.js:

<code class="language-jsx">// ... (import statements and productData) ...

const Products = () => (
  <div>
    <h2>Products</h2>
    <ul> {/* ... linkList (generated from productData) ... */} </ul>
    <routes>
      <route path=":productId" element="{<Product" data="{productData}"></route>} />
      <route index element="{<p">Please select a product.} />
    </route></routes>
  </div>
);

// ... Product component ...</code>

Add a Login component and integrate PrivateRoute into App.js to protect the /admin route. Remember the security considerations mentioned in the original response.

React Router v6.4 and Beyond:

React Router v6.4 introduced data loading and mutation APIs (inspired by Remix). These APIs simplify data fetching and management within routes using loaders and actions. This section would need a separate, more detailed explanation.

Summary:

This tutorial provided a comprehensive overview of React Router v6, covering basic and advanced routing concepts. Remember to consult the official React Router documentation for the most up-to-date information and details.

The above is the detailed content of React Router v6: A Beginner's Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn