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

React Router v6: A Beginner's Guide

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-02-08 11:33:11
Original
482 people have browsed it

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:

<Route path="/about" element={<About />} />
Copy after login
Copy after login

<Route> components can be placed anywhere within your application's structure. The simplicity of components like <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:

<Route path="/about" element={<About />} />
Copy after login
Copy after login

Create a new React project using Create React App:

node -v
npm -v
Copy after login

Install React Router DOM:

npx create-react-app react-router-demo
cd react-router-demo
Copy after login

Start the development server:

npm install react-router-dom
Copy after login

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:

npm start
Copy after login

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> renders UI if the location matches the path. <Link> provides navigation without page reloads.

Update App.js:

// src/index.js
import { BrowserRouter } from 'react-router-dom';
// ...
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);
Copy after login

This sets up basic navigation and routing.

Nested Routing:

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

Modify App.js:

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</Link></li>
          <li><Link to="/categories">Categories</Link></li>
          <li><Link to="/products">Products</Link></li>
        </ul>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/categories" element={<Categories />} />
        <Route path="/products" element={<Products />} />
      </Routes>
    </div>
  );
}
Copy after login

Create Categories.js:

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 path="/categories" element={<Categories />}>
          <Route path="desktops" element={<Desktops />} />
          <Route path="laptops" element={<Laptops />} />
        </Route>
        <Route path="/products/*" element={<Products />} /> {/* Note the trailing * */}
      </Routes>
    </div>
  );
}
Copy after login

The <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:

import { Link, Outlet } from 'react-router-dom';

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

export const Desktops = () => <h3>Desktop PC Page</h3>;
export const Laptops = () => <h3>Laptops Page</h3>;
Copy after login

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:

// ... (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 index element={<p>Please select a product.</p>} />
    </Routes>
  </div>
);

// ... Product component ...
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template