How to parse query string in react-router v4

I proffer my little ES6 shape function, awesome, light weight and useful:

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};

Every thing is here, hope to help you.


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

Thank you.


Looks like you already assumed correct. 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. The one you mentioned has worked great for me so far.

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 search = props.location.search; // could be '?foo=bar'
const params = new URLSearchParams(search);
const foo = params.get('foo'); // bar

You can read more about the decision here


Glad I found this post. Thanks for the links, after a couple of hours I finally got my code upgraded.

For those of you using query-string, you might have to do something like

var nameYouWant = queryString.parse(this.props.location.search).nameYouWant;

This happened in my case, and this.props.location.search.theUrlYouWant would refuse to work. The second option Tyler mentioned also worked for me with some similar tweaking.