Understanding the Basics of Routing in React (pt 2)

Vanessa Martinez
2 min readFeb 18, 2021

--

In my last post, I talked about setting up the React Router library to enable proper routing functionality in your React app. I covered BrowserRouter, Routes, history, component props, render props, and Switch. Now, for part 2, I’ll be discussing how to use Link.

Link

React Router comes with the capability to include links within your app. It’s written as a <Link /> component and works through the use of hyperlinks to help you navigate around your app. The best part about using it is that it will not reload the page. Instead, when clicking the <Link /> component, it will simply change the UI and update the URL.

<Link to='/mushrooms'>All Mushrooms</Link>

Notice the to prop on the <Link /> component. It points to the location where the link should take you. If you recall, in pt 1, I set up my <Route /> component so that the path ‘/mushrooms’ would render the <Mushrooms /> component. So, that takes care of what the UI will change to when you click the link.

Nested Routing

Sometimes you may need to go one level deeper in a route. For example, you may need to view one specific mushroom, so your URL would be something like:

/mushrooms/3

This is referred to as “nested routing,” and the <Link /> component works fine here too—only slightly differently than before.

We’ll first want to set up the Route path, so the <Link /> component will know where to go. If you’re navigating to an item’s show page, like below, then you will need to dynamically route to the matching ID.

Note: A match object will be created when the route’s path and location match. We will use that match object to access its params property, which contains its own object of key-value pairs.

So, in my Route path, I specify that it will route to a mushroom’s ID, and then I create a variable that will always find the matching ID based on what’s in params.

<Route  path='/mushrooms/:id' render={ (routerProps) => {const mushId = parseInt(routerProps.match.params.id)return  <MushShowPage {...routerProps} mushId={mushId} />} }/>

I have a <MushroomsContainer />, where I render each <Mushroom /> component. As I map over each individual mushroom, I also use the spread operator to pass down all the individual properties inside each mushroom object as props. One of them is the ID.

<div>{mushrooms.map(mushroom => <Mushroom key={mushroom.id} {...mushroom} />)}</div>

Now, inside <Mushroom /> I interpolate the ID inside my <Link /> to prop’s path.

<div><Link to = {`/mushrooms/${id}`}> <img src={'http://localhost:3000' + image_url} alt={name} /> </Link></div>

Since I set up how to handle a dynamic ID inside my Routes, the link knows where to route.

--

--

Vanessa Martinez

Freelance Software Engineer. Experience in JavaScript, React.js, and Ruby on Rails.