React
Layout and route
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.
Exercise 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.
Show example 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;
Test yourself
-
Where does nested route content render?
- In the useNavigate hook
- In the useParams return
- In the parent route's Outlet
- Outside BrowserRouter
Show answer
In the parent route's Outlet — The child route renders where the parent's Outlet sits.
-
StatCard destructuring
function StatCard({ ____ }) {
return (
<article>
<h3>{label}</h3>
<p>{value}</p>
</article>
);
}
Show answer
function StatCard({ label, value }) {
return (
<article>
<h3>{label}</h3>
<p>{value}</p>
</article>
);
}
-
Layout and route: match the terms
- StatCard
- Data card
- label
- Heading
- value
- Number
- article
- Container
Next lesson: Stats widget