I'm using react-router-dom 4.0.0-beta.6 in my project. I have a code like following:
<Route exact path="/home" component={HomePage}/>
And I want to get query params in HomePage
component. I've found location.search
param, which looks like this: ?key=value
, so it is unparsed.
What is the right way to get query params with react-router v4?
If you are using React Router for routing in your application, then you can use the useSearchParams hook. Here we are making use of useSearchParams to retrieve the query parameters.
We can define and use a useQuery Hook in a component to get query parameters. To pass in query parameters, we just add them to the Link s to props as usual. For example, we can write the following: We first defined the useQuery Hook to get the query parameters of the URL via the URLSearchParams constructor.
The ability to parse query strings was taken out of V4 because there have been requests over the years to support different implementation. With that, the team decided it would be best for users to decide what that implementation looks like. We recommend importing a query string lib. Here's one that I use
const queryString = require('query-string'); const parsed = queryString.parse(props.location.search);
You can also use new URLSearchParams
if you want something native and it works for your needs
const params = new URLSearchParams(props.location.search); const foo = params.get('foo'); // bar
You can read more about the decision here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With