Hello Guys,
We’ll learn how to extract the URL parameters from a current route in react using react-router in this article.
Obtaining the URL parameters
In react-router v5, we can use the useParams()
hook to grab the url parameter from a current route.
Consider the fact that we have a route similar to this in our react app.
<Route path="/users/:id" component={Users} />
Using the useParams()
hook, we can now retrieve the :id
param value from a Users
component.
Users.js:
import React from "react"; import { useParams } from "react-router-dom"; export default function Users() { const { id } = useParams(); return ( <div> <h1>User id is {id}</h1> </div> ); }
You may use props.match.params.id
in React router v4 to get to it.
Users.js:
import React from "react"; import { useParams } from "react-router-dom"; export default function Users(props) { const { id } = props.match.params; return ( <div> <h1>User id is {id}</h1> </div> ); }