6

This may sound dump, but how I am supposed to read the URL and get its values from an URL in React JS. I have been told to use the QueryString in order to handle the GET parameters.

The Url looks has following structure:

localhost/test?id=xxx&value=yyyy

in the component class I'm using following code:

class test extends Component {

  func() {
    const params = queryString.parse(location.search);

     //here I get: {?id=xxx&value=yyyy}
  }
}

How does it come that the Questionmark Sign has been retrived also? And how to fix it, so that I am able to get those values without crafting too much?

Christian Felix
  • 644
  • 1
  • 9
  • 28
  • @Ashish, the question is the same, but the answer does not fit fully my requirements. I do not want to use window.location.search when there is some npm libraries which may handle it in much better way- – Christian Felix May 13 '19 at 12:52
  • Just for the sake of getting parameters, i dont think using any library is good idea. When you can achieve this with a small util function of your own. I would prefer that. – Ashish May 13 '19 at 16:11

2 Answers2

15

You can use URLSearchParams:

const windowUrl = window.location.search;
const params = new URLSearchParams(windowUrl);
// params['id']

Or, if you desire to use react-router solutions, you can see this answer.

AdamGold
  • 4,941
  • 4
  • 29
  • 47
5

If you're utilizing react-router, it's pretty easy. See this: https://tylermcginnis.com/react-router-query-strings/

Katia Wheeler
  • 519
  • 3
  • 8
  • Do I have to use the react-router, even if I only want to retrive the url without doing anything else? For some reason accessing the params.id results in undefined.. – Christian Felix May 13 '19 at 12:44
  • 1
    If you don't want to use `react-router` you could try this library: https://www.npmjs.com/package/query-string – Katia Wheeler May 13 '19 at 12:47
  • I'm using it already.. but the question is: how to get the individual values from it? – Christian Felix May 13 '19 at 12:49
  • 1
    If you use the `query-string` pacakge, it has a `.parse()` function that creates an object from the query string of the URL. So, let's say the url was `?search=something?dog=cat`. After calling the `parse` method, you would have an object like the following `{ search: 'something', dog: 'cat' } ` that you could access the individual properties from where you need them – Katia Wheeler May 13 '19 at 12:55
  • for some reason I was using the querystring not the query-string package..Not sure if there are any significant differences. Right now, I will remove the prevous one and install the query-string for that... maybe its the reason why the ignoreQueryPrefix: true Parameter has worked as expected. – Christian Felix May 13 '19 at 13:14
  • the problem was obvious the package.. Right now it works and I'm able to read the indvidual values. – Christian Felix May 13 '19 at 13:38