To implement nested routes in React Router and pass data between routes effectively, follow these steps:
1. Set Up Nested Routes
Use the Outlet component from react-router-dom to render nested routes within a parent route.
import { BrowserRouter, Routes, Route, Outlet } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="parent" element={<Parent />}>
<Route path="child" element={<Child />} />
</Route>
</Route>
</Routes>
</BrowserRouter>
);
}
function Layout() {
return (
<div>
<h1>Layout</h1>
<Outlet /> {/* Nested routes render here */}
</div>
);
}
function Home() {
return <h2>Home</h2>;
}
function Parent() {
return (
<div>
<h2>Parent</h2>
<Outlet /> {/* Child route renders here */}
</div>
);
}
function Child() {
return <h3>Child</h3>;
}
2. Pass Data Between Routes
You can pass data between routes using:
a. URL Parameters
Use useParams to access dynamic segments in the URL.
<Route path="parent/:id" element={<Parent />} />
function Parent() {
const { id } = useParams();
return <h2>Parent ID: {id}</h2>;
}
b. State via useNavigate or Link
Pass state when navigating using useNavigate or <Link>.
import { Link, useLocation } from 'react-router-dom';
function Parent() {
const navigate = useNavigate();
const data = { message: "Hello from Parent" };
return (
<div>
<button onClick={() => navigate('child', { state: data })}>
Go to Child
</button>
<Link to="child" state={data}>Go to Child</Link>
</div>
);
}
function Child() {
const location = useLocation();
const { message } = location.state || {};
return <h3>Child: {message}</h3>;
}
c. Context API or State Management
For complex data sharing, use React Context or state management libraries like Redux.
3. Access Data in Nested Routes
Use useParams, useLocation, or context to access data in nested routes.
function Child() {
const { id } = useParams();
const location = useLocation();
const { message } = location.state || {};
return (
<div>
<h3>Child ID: {id}</h3>
<p>Message: {message}</p>
</div>
);
}