Question

How to get query string using React?

I'm trying to get "query=123" from the url http://localhost:3000/?query=123. Tried

//App.js
const search = this.props.location.search;
const params = new URLSearchParams(search);
const foo = params.get('foo');

console.log(this.props);

and my console shows this https://d.pr/i/w5tAYF which doesn't show location.search anywhere... any idea how I would get the query string?

 46  70076  46
1 Jan 1970

Solution

 104

React doesn't handle URL search parameters. You need to look in the window object for them instead. Here's how you would get the value of query:

let search = window.location.search;
let params = new URLSearchParams(search);
let foo = params.get('query');
2018-10-04

Solution

 5

I created a separate function for the query string.

function useQuery() {
  return new URLSearchParams(window.location.search);
}

Then I can provide the query string I want to get. In your case its query

  let query = useQuery().get('query');
2020-07-01