46

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?

2
  • the reason is when i tried to log this.props.location, it's undefined. please check my image shown for this.props Commented Oct 4, 2018 at 17:49
  • 5
    this.props.location.search doesn't contain the query. You need to look in window.location.search. Commented Oct 4, 2018 at 17:52

5 Answers 5

105

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');
Sign up to request clarification or add additional context in comments.

3 Comments

new URLSearchParams(search).get('foo') is not working for some reason
i'm getting null. here's a screenshot of const params d.pr/i/r5GcHM
You need to change it to get('query'). I was using foo as an example. I've corrected my answer.
4

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

Comments

3

Within your component, you can do something like this:

const values = queryString.parse(this.props.location.search)
console.log(values.filter) 
console.log(values.origin) 

There is more here.

1 Comment

OP doesn't seem to be using React Router.
2

import { useLocation } from "react-router-dom";

const search = useLocation().search;
console.log('path', search);
const id = new URLSearchParams(search).get("id");
console.log(id);

Comments

0

If you want to get query params from a custom URL, not the currently opened URL, you can use the code below.

const customURL = 'https://custom.url.com?success=true'
const params = new URLSearchParams(customURL.split('?')[1])

const successParamValue = params.get('success')

If you are using React Native you will need additional step to support URLSearchParams. Just install below package. that's it!

npm install react-native-url-polyfill

or

yarn add react-native-url-polyfill

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.