Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get query parameters in react-router v4

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?

like image 682
andrfas Avatar asked Apr 04 '17 19:04

andrfas


People also ask

How do I get query parameters in react router?

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.

How do you use query parameters in react?

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.


1 Answers

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

like image 148
Tyler McGinnis Avatar answered Sep 29 '22 16:09

Tyler McGinnis