Sub topic 2
Nested Routes and URL-Driven UI
Assume you know React function components, JSX, hooks, and basic URL structure. This chapter uses React Router's data-router API.
Nested Routes and Shared Layouts with `Outlet`
A nested route renders inside its parent route. The parent usually contains shared UI, such as navigation. The Outlet component marks the location where the matching child appears.
import {
createBrowserRouter,
RouterProvider,
Link,
Outlet,
useNavigate,
useParams,
useSearchParams,
} from "react-router-dom";
function Layout() {
return (
<>
<nav>
<Link to="/">Home</Link>{" "}
<Link to="/users/42?tab=posts">User</Link>
</nav>
<Outlet />
</>
);
}
function Home() {
const navigate = useNavigate();
return <button onClick={() => navigate("/users/42")}>Open user</button>;
}
function User() {
const { userId } = useParams();
const [params, setParams] = useSearchParams();
const tab = params.get("tab") ?? "profile";
return (
<>
<h1>User {userId}</h1>
<p>Current tab: {tab}</p>
<button onClick={() => setParams({ tab: "posts" })}>
Show posts
</button>
</>
);
}
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{ index: true, element: <Home /> },
{ path: "users/:userId", element: <User /> },
{ path: "*", element: <h1>Not found</h1> },
],
},
]);
export default function App() {
return <RouterProvider router={router} />;
}An index route has index: true. It renders at the parent's exact path, so the Home component renders at /. A splat route, written as *, matches otherwise-unmatched paths and provides a route-level 404 page.
Dynamic Segments and Query Strings
A dynamic segment starts with :. For /users/42, useParams() returns { userId: "42" }. Parameters are strings, so convert them when you need a number.
Search parameters follow ? in a URL. useSearchParams reads and updates them. Updating the parameters also updates the URL and re-renders the route.
Navigating from Code
Use Link for user-initiated navigation. Use useNavigate after an event or completed operation, such as saving a form. Both update the browser history without a full page reload.
Exercise
What renders at /users/42?tab=posts?
Show answer
Layout renders first, then User renders inside its Outlet; userId is "42" and tab is "posts".