Home >Web Front-end >JS Tutorial >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:
<routes></routes>
, <route></route>
, and <link>
, including the use of path parameters for flexible routing.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:
www.example.com/products
).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:
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.
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>
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.
<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!