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 />} />
<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:
- Setting up React and React Router using npm.
- Basic routing concepts.
- Nested routing.
- Dynamic nested routing with path parameters.
- 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 />} />
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.
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
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> );
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.
