Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read URL Parameters within Component in React JS? [duplicate]

Tags:

reactjs

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?

like image 962
Christian Felix Avatar asked Dec 06 '22 09:12

Christian Felix


1 Answers

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.

like image 113
AdamGold Avatar answered Jan 11 '23 23:01

AdamGold