Code a React app to demo Client-Side Route Params & the useParams
hook.
-
Create a new React-based project in StackBlitz.
-
Add
react-router
as a dependency by:
- Shutting down the React development server in the terminal with
[ctrl]
+[c]
- Running
npm i react-router
- Restarting the developerment server with
npm run dev
- In src/main.jsx:
import { BrowserRouter as Router } from "react-router";
- Wrap
<App />
with<Router>
- Code a simple
<Home>
component in a new HomePage.jsx module:
export default function HomePage() {
return <h1>Home Page</h1>;
}
- In App.jsx
import { Routes, Route } from "react-router";
and alsoimport HomePage from "./HomePage";
. Then write the code to render the<HomePage>
component at the root route.
<Routes>
<Route path="/" element={<HomePage />} />
</Routes>
Verify that the <HomePage>
component is rendering
- Ordinarily, you would want to code a separate
<NavBar>
component, but in the spirit of saving a bit of time, we will include a<nav>...</nav>
React element above<Routes>
within App.jsx. Be sure to addLink
to the list of imports ({ Routes, Route, Link }
):
<nav>
<Link to="/">HOME</Link>
|
<Link to="/menu/burritos">BURRITOS</Link>
|
<Link to="/menu/tacos">TACOS</Link>
</nav>
- In App.jsx, let's define a single additional
<Route>
with a route parameter to match any number of menu categories (burritos, tacos, etc.) and renders a<MenuPage>
component.
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/menu/:category" element={<MenuPage />} /> // <-- add this route
</Routes>
Note that
<nav>
will always render since it's not within the<Routes>
component and, as a reminder, only a single<Route>
component gets rendered by<Routes>
.
- So, we need that
<MenuPage>
component - create a MenuPage.jsx module for it and import it in App.jsx as usual. Within MenuPage.jsx, be sure to importuseParams
and put it to use in the function to access thecategory
route parameter:
// MenuPage.jsx
import { useParams } from "react-router";
export default function MenuPage() {
// useParams() returns an object containing a property
// for each route parameter defined in the matching Route's path
const { category } = useParams();
return <h1>Menu - {category.toUpperCase()}</h1>;
}