How to get query parameters in react-router v4

andrfas picture andrfas · Apr 4, 2017 · Viewed 89k times · Source

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?

Answer

Tyler McGinnis picture Tyler McGinnis · Apr 5, 2017

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