react-router / useParams

useParams, how do you React?

My adventures in React-Router

Alex Amersi-Belton

--

As I continue my journey from tech-banker to software engineer, a month or so has rolled by and I have hit project mode again. The focus of my studies has been around the React framework and how to build web apps in a Declarative way.

Photo by Nubelson Fernandes on Unsplash

This time the learning curve when compared to what I had experienced in the first part of my bootcamp (which took me from from zero JavaScript experience to making something functional) was significantly smoother.

The React framework and it’s component based approach really clicked with me, coming into it after the libraryhas been out for so long meant that my start point has been using hooks and functional components straight out of the box. While a working knowledge of class based components has been acquired, hooks has me, well, hooked!

As mentioned, project mode is upon me, and the task is seemingly simple yet broadly scoped as to be rather intimidating, that being — Using create-react-app, make a single page app, that uses multiple components and client side routes which also interacts with an API, either your own or a public one. Sounds so straight forward, however the sheer openness of the brief meant settling on a topic was somewhat overwhelming. What topic would you choose to build out if you were in this position? Put it in the comments below, I’d love to hear.

I guess I should reveal what I settled on: I chose to create an art gallery, my vision was a landing page with the intro to the art gallery, a gallery page and an about the artist page, three simple ‘pages’ to link my client side routes to in the gallery webapp.

Upon reading the React Router documentation the hook useParams jumped out to me as a potential stretch goal — what if each artwork in my gallery could have a separate and defined URL?

How it works

How useParams works in react router, the documentation for it is pretty clear, but in essence useParams allows you to hook into a URL and take part of it as your parameter to use in a component. This is represented by :<param> to signify it in the URL path, in the example below if an image is requested from the URL “./images/42" the corresponding <div> upon render will on display show the text “Now showing image 42”

import {
BrowserRouter as Router,
Switch,
Route,
useParams
} from "react-router-dom";
function DisplayImage() {
let { id } = useParams();
return <div>Now showing image {id}</div>
<Router>
<Switch>
<Route exact path="/">
<HomePage />
</Route>
<Route path="/images/:id">
<DisplayImage />
</Route>
<Switch>
</Router>

The useParams hook is taking the specified URL element and setting it it to capture it and use it to fulfill parts of your component. In my app I used it to capture the API JSON array position and use it to GET the specific image so you could zoom in on the artworks and find out a bit more about them from the gallery view. This led to unique links to all my artworks, pretty snazzy I’m sure you’ll agree.

Handling errors

Utilising this method meant I now had all the images with unique links, which could directly access and render the images. One error I found through testing was that as it was trying to GET an image and pass it to a second component as a prop, the second component would always render, thus a bad link :id would not throw an error out and stop the page rendering as intended. It would pass an empty array as the prop which just left empty div elements and a bit of formatting, not a good look.

Some google-fu later I learnt that a GET request that results in a status 404: file not found error message still completes a fetch(GET) promise so will not throw an error to a .catch request, thats saved for server errors only. So I had to add an IF condition to my fetch response so if it was outside the usual means I would throw the element to the nearest .catch in the request.

How I handled my error, by throwing it to another place

As my code block above shows this is then set to a state variable which could be monitored and if something went into it and increased the state.length I could render a different error page or otherwise render the image display component. It then also allowed me to have a simple method to have a loading message in the other component when the props were taking their time to be fulfilled and display within the component. (Yay latency!)

The TL/DR

useParams is an incredibly useful part of react router which allows you to create individual links while using minimal code and keeping things organised in the Router Switch statement. Just watch out for errors.

Once the project goes live I will update with links so you too can take a walk through the galleries.

As always get in touch if you want to know more about my projects or me in general!

--

--

Alex Amersi-Belton

Former tech banker, now aspiring software engineer. Feel free to get in touch.