score:158

Accepted answer

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');

score:0

you may get the following error while creating an optimized production build when using query-string module.

failed to minify the code from this file: ./node_modules/query-string/index.js:8

to overcome this, kindly use the alternative module called stringquery which does the same process well without any issues while running the build.

import querysearch from "stringquery";

var query = querysearch(this.props.location.search);

score:3

simple js solution:

querystringparse = function(string) {
    let parsed = {}
    if(string != '') {
        string = string.substring(string.indexof('?')+1)
        let p1 = string.split('&')
        p1.map(function(value) {
            let params = value.split('=')
            parsed[params[0]] = params[1]
        });
    }
    return parsed
}

and you can call it from anywhere using:

var params = this.querystringparse(this.props.location.search);

hope this helps.

score:4

after reading the other answers (first by @duncan-finney and then by @marrs) i set out to find the change log that explains the idiomatic react-router 2.x way of solving this. the documentation on using location (which you need for queries) in components is actually contradicted by the actual code. so if you follow their advice, you get big angry warnings like this:

warning: [react-router] `context.location` is deprecated, please use a route component's `props.location` instead.

it turns out that you cannot have a context property called location that uses the location type. but you can use a context property called loc that uses the location type. so the solution is a small modification on their source as follows:

const routecomponent = react.createclass({
    childcontexttypes: {
        loc: proptypes.location
    },

    getchildcontext() {
        return { location: this.props.location }
    }
});

const childcomponent = react.createclass({
    contexttypes: {
        loc: proptypes.location
    },
    render() {
        console.log(this.context.loc);
        return(<div>this.context.loc.query</div>);
    }
});

you could also pass down only the parts of the location object you want in your children get the same benefit. it didn't change the warning to change to the object type. hope that helps.

score:10

with stringquery package:

import qs from "stringquery";

const obj = qs("?status=approved&page=1limit=20");  
// > { limit: "10", page:"1", status:"approved" }

with query-string package:

import qs from "query-string";
const obj = qs.parse(this.props.location.search);
console.log(obj.param); // { limit: "10", page:"1", status:"approved" } 

no package:

const converttoobject = (url) => {
  const arr = url.slice(1).split(/&|=/); // remove the "?", "&" and "="
  let params = {};

  for(let i = 0; i < arr.length; i += 2){
    const key = arr[i], value = arr[i + 1];
    params[key] = value ; // build the object = { limit: "10", page:"1", status:"approved" }
  }
  return params;
};


const uri = this.props.location.search; // "?status=approved&page=1&limit=20"

const obj = converttoobject(uri);

console.log(obj); // { limit: "10", page:"1", status:"approved" }


// obj.status
// obj.page
// obj.limit

hope that helps :)

happy coding!

score:14

"react-router-dom": "^5.0.0",

you do not need to add any additional module, just in your component that has a url address like this:

http://localhost:3000/#/?authority'

you can try the following simple code:

    const search =this.props.location.search;
    const params = new urlsearchparams(search);
    const authority = params.get('authority'); //

score:17

update 2017.12.25

"react-router-dom": "^4.2.2"

url like

browserhistory: http://localhost:3000/demo-7/detail/2?sort=name

hashhistory: http://localhost:3000/demo-7/#/detail/2?sort=name

with query-string dependency:

this.id = props.match.params.id;
this.searchobj = querystring.parse(props.location.search);
this.from = props.location.state.from;

console.log(this.id, this.searchobj, this.from);

results:

2 {sort: "name"} home


"react-router": "^2.4.1"

url like http://localhost:8080/react-router01/1?name=novaline&age=26

const queryparams = this.props.location.query;

queryparams is a object contains the query params: {name: novaline, age: 26}

score:59

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

score:62

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


Related Query

More Query from same tag