Getting query parameters from react-router hash fragment
OLD (pre v4):
Writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. I use this command to lookup the query params in my components:
this.props.location.query
It creates a hash of all available query params in the url.
UPDATE (React Router v4+):
this.props.location.query in React Router 4 has been removed (currently using v4.1.1) more about the issue here: https://github.com/ReactTraining/react-router/issues/4410
Looks like they want you to use your own method to parse the query params, currently using this library to fill the gap: https://github.com/sindresorhus/query-string
Note: Copy / Pasted from comment. Be sure to like the original post!
Writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. I use this command to lookup the query params in my components:
this.props.location.query
It creates a hash of all available query params in the url.
Update:
For React-Router v4, see this answer. Basically, use this.props.location.search
to get the query string and parse with the query-string
package or URLSearchParams:
const params = new URLSearchParams(paramsString);
const tags = params.get('tags');
The above answers won't work in react-router v4
. Here's what I did to solve the problem -
First Install query-string which will be required for parsing.
npm install -save query-string
Now in the routed component you can access the un-parsed query string like this
this.props.location.search
You can cross check it by logging in the console.
Finally parse to access the query parameters
const queryString = require('query-string');
var parsed = queryString.parse(this.props.location.search);
console.log(parsed.param); // replace param with your own
So if query is like ?hello=world
console.log(parsed.hello)
will log world