7

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?

2
  • @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- Commented May 13, 2019 at 12:52
  • 1
    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. Commented May 13, 2019 at 16:11

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

1 Comment

react-router is my desired approach. For now I just only wanted to read the GET paramaters.
6

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

6 Comments

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..
If you don't want to use react-router you could try this library: npmjs.com/package/query-string
I'm using it already.. but the question is: how to get the individual values from it?
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
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.