Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Last active January 16, 2025 22:40
Show Gist options
  • Save jim-clark/818e418fbe5851568f84d2e1ab5a4958 to your computer and use it in GitHub Desktop.
Save jim-clark/818e418fbe5851568f84d2e1ab5a4958 to your computer and use it in GitHub Desktop.

React Router Route Params/useParams Practice Exercise

Code a React app to demo Client-Side Route Params & the useParams hook.

Instructions

  1. Create a new React-based project in StackBlitz.

  2. 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
  1. In src/main.jsx:
  • import { BrowserRouter as Router } from "react-router";
  • Wrap <App /> with <Router>
  1. Code a simple <Home> component in a new HomePage.jsx module:
export default function HomePage() {
  return <h1>Home Page</h1>;
}
  1. In App.jsx import { Routes, Route } from "react-router"; and also import 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

  1. 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 add Link to the list of imports ({ Routes, Route, Link }):
<nav>
  <Link to="/">HOME</Link>
  &nbsp;&nbsp;|&nbsp;&nbsp;
  <Link to="/menu/burritos">BURRITOS</Link>
  &nbsp;&nbsp;|&nbsp;&nbsp;
  <Link to="/menu/tacos">TACOS</Link>
</nav>
  1. 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>.

  1. 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 import useParams and put it to use in the function to access the category 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>;
}

Test it out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment