Sometimes, we want to get parameter value from query string with React Router.
In this article, we’ll look at how to get parameter value from query string with React Router.
How to get parameter value from query string with React Router?
To get parameter value from query string with React Router, we can use the useLocation
hook.
For instance, we write
import React from "react";
import { useLocation } from "react-router-dom";
const MyComponent = () => {
const { search } = useLocation();
const id = new URLSearchParams(search).get("id");
console.log(id);
//...
};
to use the useLocation
hook to get the URL data.
And then we get the query string from the search
property.
Next, we pass in search
to URLSearchParams
.
And we get the value of the id
query parameter with get
.
Conclusion
To get parameter value from query string with React Router, we can use the useLocation
hook.