73

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

In react-router-dom@4.0.0 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)

Peter Bengtsson
  • 7,235
  • 8
  • 44
  • 53

10 Answers10

155

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

Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77
24

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.

AmerllicA
  • 29,059
  • 15
  • 130
  • 154
  • Thumbs up because Internet Explorer STILL doesn't support [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams). WTF Bill Gates. – BigRon Jun 22 '21 at 19:41
  • 1
    @BigRon, Thanks for your upvote, I know, we should use something like this because of backward compatibility and support legacy browsers but sometimes we should have a covenant or contract to Boycott this shitty annoying thing. In my current project I never check IE even Edge. this is a world project a new Social Network – AmerllicA Jun 22 '21 at 19:51
20

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.

Balasubramani M
  • 7,742
  • 2
  • 45
  • 47
  • 2
    To get around this, you can also use an older version of `query-string`. You can install it by either doing `yarn add query-string@5` or `npm install query-string@5` – MoonDawg Aug 30 '18 at 02:32
7

Using third party package is overkill for a simple problem:

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 the URL query parameters into an object.

kelsny
  • 23,009
  • 3
  • 19
  • 48
midnightgamer
  • 444
  • 1
  • 5
  • 18
6

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.

DORRITO
  • 621
  • 2
  • 8
  • 25
4

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...}

samad324
  • 199
  • 6
4

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

Fábio Batista
  • 25,002
  • 3
  • 56
  • 68
Thomas
  • 6,291
  • 6
  • 40
  • 69
3

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)
zhulien
  • 5,145
  • 3
  • 22
  • 36
Lucas
  • 9,871
  • 5
  • 42
  • 52
0

In addition to the answer already provided here, you can make it into a hook:

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

const useParsedSearchParams = () => {
    const [searchParams] = useSearchParams();

    return Object.fromEntries([...searchParams]);
};

export default useParsedSearchParams;
Mike K
  • 7,621
  • 14
  • 60
  • 120
-1

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])
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 11 '22 at 03:30