How to parse query string in react-router v4

ReactjsReact RouterReact Router-Dom

Reactjs Problem Overview


In react-router v3 I could access it with props.location.query.foo (if the current location was ?foo=bar)

In [email protected] props.location only has props.location.search with is a string like ?foo=bar&other=thing.

Perhaps I need to manually parse and deconstruct that string to find the value for foo or other.

Screenshot of console.log(this.props): enter image description here (Note how from ?artist=band here I'd like to get the value from artist which is the value band)

Reactjs Solutions


Solution 1 - Reactjs

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

Solution 2 - Reactjs

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.

Solution 3 - Reactjs

You may get the following error while creating an optimized production build when using [query-string][1] 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][2] 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. [1]: https://www.npmjs.com/package/query-string [2]: https://www.npmjs.com/package/stringquery

Solution 4 - Reactjs

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.

Solution 5 - Reactjs

Using third party package is overkill to simple solutions

componentDidMount() {
        const query = new URLSearchParams(
            this.props.location.search
        );

        let data= {};

        for (let params of query.entries()) {
            data[params[0]] = +params[1];
        }
        this.setState({ urldata: data});
    }

this will simply convert URL data into object.

Solution 6 - Reactjs

I'm surprised no one has mentioned UrlSearchParams and the .get method.

Solution 7 - Reactjs

instead of installing a package you can use a simple function for extracting your query params.

//Param Extractor
const parseParams = (params = "") => {
  const rawParams = params.replace("?", "").split("&");
  const extractedParams = {};
  rawParams.forEach((item) => {
    item = item.split("=");
    extractedParams[item[0]] = item[1];
  });
  return extractedParams;
};

//Usage
const params = parseParams(this.props?.location?.search); // returns an object like:
// {id:1,name:john...}

Solution 8 - Reactjs

Late answer for case of getting query string with react routers useLocation:

 import useLocation from 'react-router';
 import queryString from 'query-string';

 const handleQueryString = useLocation().search;
 // nice=day&very=sunny
 
 // Get a param
 const { nice } = queryString.parse(useLocation().search)

Solution 9 - Reactjs

> use useSearchParams instead of location.search in react-router-v6

import { useSearchParams } from 'react-router-dom';

const Chat = ({location}) => {

  const [searchParams] = useSearchParams();

  // pass searchParams as a dependency into the useEffect
  useEffect(()=>{
    const currentParams = Object.fromEntries([...searchParams])

    console.log(currentParams);
  },[searchParams])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeter BengtssonView Question on Stackoverflow
Solution 1 - ReactjsTyler McGinnisView Answer on Stackoverflow
Solution 2 - ReactjsAmerllicAView Answer on Stackoverflow
Solution 3 - ReactjsBalasubramani MView Answer on Stackoverflow
Solution 4 - ReactjsDORRITOView Answer on Stackoverflow
Solution 5 - ReactjsmidnightgamerView Answer on Stackoverflow
Solution 6 - ReactjsThomasView Answer on Stackoverflow
Solution 7 - Reactjssamad324View Answer on Stackoverflow
Solution 8 - ReactjsLucasView Answer on Stackoverflow
Solution 9 - Reactjskhurshida alamView Answer on Stackoverflow