Layout and route
- React course
- Intermediate
- Lesson 74/80
- 5 min
Set up the DashboardLayout and nested routes.
Stats route
In this lesson we add a stats widget to the /stats route. The layout was built in the previous lesson; now the content comes.
In React Router, nested routes work by rendering <Outlet> in the parent route's element. The child route's element is shown based on the URL.
Here we add a simple StatsPage to fill with StatCard later.
StatCard skeleton
The StatCard component takes { label, value } props. It renders an <article> containing an <h3> and a <p>. This structure shows data cleanly.
Props are destructured: function StatCard({ label, value }). This is shorter and more readable than writing props.label.
This lesson's starting code includes the previous layout solution; you add StatCard and use it in StatsPage.
Practice StatsPage and StatCard
Write StatCard: destructure { label, value }, render <article> with <h3>{label}</h3> and <p>{value}</p>. Write StatsPage: render two <StatCard>s (label="Users" value=120 and label="Orders" value=45). In DashboardApp, set the path="stats" route's element to <StatsPage />. export default DashboardApp.
Starter code
import { BrowserRouter, Routes, Route, NavLink, Outlet } from "react-router-dom";
// StatCard ve StatsPage bileşenlerini buraya yaz, sonra DashboardApp'i güncelleSample solution
import { BrowserRouter, Routes, Route, NavLink, Outlet } from "react-router-dom";
function StatCard({ label, value }) {
return (
<article>
<h3>{label}</h3>
<p>{value}</p>
</article>
);
}
function StatsPage() {
return (
<section>
<StatCard label="Users" value={120} />
<StatCard label="Orders" value={45} />
</section>
);
}
function DashboardLayout() {
return (
<>
<nav>
<NavLink to="/stats">Stats</NavLink>
</nav>
<main>
<Outlet />
</main>
</>
);
}
function DashboardApp() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<DashboardLayout />}>
<Route path="stats" element={<StatsPage />} />
</Route>
</Routes>
</BrowserRouter>
);
}
export default DashboardApp;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where does nested route content render?
- In the useNavigate hook
- In the useParams return
- In the parent route's Outlet Correct answer
- Outside BrowserRouter
Explanation: The child route renders where the parent's Outlet sits.
2 StatCard destructuring
function StatCard({ ____ }) {
return (
<article>
<h3>{label}</h3>
<p>{value}</p>
</article>
);
}
function StatCard({ label, value }) {
return (
<article>
<h3>{label}</h3>
<p>{value}</p>
</article>
);
}
Explanation: label and value are destructured.
3 Layout and route: match the terms
| Term | Meaning |
|---|---|
StatCard |
Data card |
label |
Heading |
value |
Number |
article |
Container |