Using React Router useParams to fetch data with dynamic URLs

Alexis Liu
3 min readOct 4, 2021

--

React Router is a library that allows for dynamic routing by conditionally rendering components depending on the route being used in the URL, and also by fetching api calls based on route parameters.

The useParams hook was shipped with React Router v5 as a way to access params in an URL. According to the documentation:

useParams returns an object of key/value pairs of URL parameters. Use it to access match.params of the current <Route>.

The useParams hook gives us access to the match.params of the route, making it really easy to access the correct routes and fetch the right data for rendering components. For example, given the code below, if a user clicks on the route to creatures/3, with routing and useParams() they’ll be able to see the <CreatureDetail/> for the third creature object in the api.

<Route path="/creatures/:id"> <CreatureDetail/> </Route>

Let’s use React Router to dynamically link and render routes to different sea creatures. (courtesy of Animal Crossing API)

  1. First, install React Router:npm install react-router-dom
  2. Import BrowserRouter from React Router and set up basic routing by using <Switch>, <Route>, and <Link> elements.
import {BrowserRouter as Router, Switch, Route } from ‘react-router-dom’;

3. Render the page. I’ve mapped over the JSON object array from the api and to render creature.name for each creature.

creatures.map((creature) => (<h2 key={creature.id}> {creature.name} </h2>)

4. To link these names to their own page of creature details, wrap a <Link> element around each name. Since we want to access the creature we click on when we go to creatures/1, creatures/2, creatures/3, etc. interpolate ${creature.id} at the end of the link path. Don’t forget to create a route as well—when the browser goes to creatures/{creature.id}, the page will render the component specified.

// Add the route:  <Route path="/creatures/:id"> <CreatureDetail/> </Route>

5. Import { useParams } from ‘react-router-dom’.

As seen in the console.log, useParams returns an object of the Route parameters. This means we can deconstruct the id with { id } = useParams() to grab the id of the path and use the id param to dynamically fetch data from the api.

Finished! Enjoy those sea creatures! 🐚

Unlisted

--

--