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:
<Route path="/about" element={<About />} />
<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:
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 />} />
Create a new React project using Create React App:
node -v npm -v
Install React Router DOM:
npx create-react-app react-router-demo cd react-router-demo
Start the development server:
npm install react-router-dom
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:
npm start
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>
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> );
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> ); }
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> ); }
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>;
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 ...
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!