It is common to use the value of URL parameters to determine what is displayed in the component that a dynamic route renders. For example, the Article
component might need to display the title of the current article.
React Router provides a hook, useParams()
, for accessing the value of URL parameters. When called, useParams()
returns an object that maps the names of URL Parameters to their values in the current URL.
For example, consider the Articles
component below which is rendered when by a route with the dynamic URL '/articles/:title'
. Consider the following Article
component, that will render when a user visits /articles/objects
:
import { Link, useParams } from 'react-router-dom'; export default function Article() { let { title } = useParams(); // title will be equal to the string 'objects' // The title will be rendered in the <h1> return ( <article> <h1>{title}</h1> </article> ); }
Let’s break down the example above.
- First, the
useParams()
hook is imported fromreact-router-dom
. - Then, inside the
Article
component,useParams()
is called which returns an object. - Destructuring assignment is then used to extract the value of the URL parameter from that object, storing it in a variable named
title
. - Finally, this
title
value is used to display the name of the article in the<h1>
element.
Let’s practice using URL parameters in our components.
Instructions
Task 1
You may have noticed that navigating to the various /articles/:title
paths will render an Article
component that displays the proper article. However, this doesn’t work as well when navigating to a specific author’s page.
Take a look at the Article.js file and you can see that the useParams()
hook has been imported and used. Let’s do the same thing with the Author.js file.
First, in Author.js, import useParams
from 'react-router-dom'
.
Hint
Use the named import syntax:
import { value } from 'name-of-package';
Task 2
Now, at the top of the Author
component, call useParams()
to get the value of the :name
URL parameter. You should use destructuring syntax to extract the value into a variable called name
.
Hint
To get the value of a particular URL parameter, use destructuring assignment like so:
const { nameOfParameter } = useParams();
Task 3
Now that you have the value of name
, let’s use it to display the correct data in the Author
component.
First, on the line where we define author
, replace the string "replace me"
with the variable name
.
Next, in between the <h1>
tags we’ve provided, replace the text “REPLACE ME” with {name}
.
To test that your code works, navigate to an article and click on its author. The Authors page should display the name that you just clicked on.
Hint
Watch the video to see how to complete this step!