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?
Solution 1:
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
Solution 2:
Another useful approach could be to use the out of the box URLSearchParams
like this;
let { search } = useLocation();
const query = new URLSearchParams(search);
const paramField = query.get('field');
const paramValue = query.get('value');
Clean, readable and doesn't require a module. More info below;
- https://reacttraining.com/react-router/web/example/query-parameters
- https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Solution 3:
The given answer is solid.
If you want to use the qs module instead of query-string (they're about equal in popularity), here is the syntax:
const query = qs.parse(props.location.search, {
ignoreQueryPrefix: true
})
The ignoreQueryPrefix
option is to ignore the leading question mark.
Solution 4:
The accepted answer works well but if you don't want to install an additional package, you can use this:
getUrlParameter = (name) => {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
let regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
let results = regex.exec(window.location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
Given http://www.google.co.in/?key=value
getUrlParameter('key');
will return value