If you have a URL with a dynamic value and you want to capture that value in your code, you can use useParam()
from React Router 5.
Let’s say we have the following URL with the user Id at the end: https://www.somesite.com/users/8bbb7b19-e055-4501-8cec-bb9d9d006de2
.
The last part of the URL (8bbb7b19-e055-4501-8cec-bb9d9d006de2
) is the dynamic value. So our route would be composed as follows:
<Route path="/users/:userId">
<Home>
</Route>
In the component we would would capture the user id as follows:
import React, {useState} from 'react';
import {useParams} from 'react-router-dom';
const MyComponent = () => {
const {userId} = userParams();
}
export default MyComponent;
We use destructuring to extract the value of userId
. Since we defined the dynamic parameter as userId
, useParams()
will extract the value of userId
in the URL.