In React, nested routes allow you to structure your routes hierarchically, where one route is nested inside another. This is useful when building complex UIs where certain components or pages are shared across different routes.
To create nested routes, you can use React Router, a popular library for handling routing in React applications.
npm install react-router-dom
import { BrowserRouter as Router, Routes, Route, Outlet, Link } from 'react-router-dom'; // Layout Component with Nested Routes function Layout() { return ( <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/dashboard">Dashboard</Link> </li> </ul> </nav> {/* This is where nested routes will be rendered */} <Outlet /> </div> ); } // Components for each route function Home() { return <h2>Home Page</h2>; } function About() { return <h2>About Page</h2>; } function Dashboard() { return ( <div> <h2>Dashboard</h2> <nav> <ul> <li> <Link to="stats">Stats</Link> </li> <li> <Link to="settings">Settings</Link> </li> </ul> </nav> {/* Nested routes inside Dashboard */} <Outlet /> </div> ); } function Stats() { return <h2>Dashboard Stats</h2>; } function Settings() { return <h2>Dashboard Settings</h2>; } // App Component with Routes function App() { return ( <Router> <Routes> <Route path="/" element={<Layout />}> <Route index element={<Home />} /> <Route path="about" element={<About />} /> <Route path="dashboard" element={<Dashboard />}> <Route path="stats" element={<Stats />} /> <Route path="settings" element={<Settings />} /> </Route> </Route> </Routes> </Router> ); } export default App;
This structure allows you to have a common layout (like a dashboard menu) and dynamically load specific sections like stats or settings based on the nested routes.
The above is the detailed content of Understanding Nested Routes in React: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!