Reputation: 20222
For now, I am rendering a React Component with a static URL.
I would like to pass it a dynamic URL.
For instance, rather than calling it like this:
https://www.example.com
I would like to call it like this:
https://www.example.com/?name=John
And I would like this to update its this.props.name
or this.state.name
components.
Can I do that?
What should I use for this purpose? react-router
?
Or can this only be done from the backend?
Upvotes: 3
Views: 4238
Reputation: 149
You do not need react-router. Following would parse your url:
let url_parameter = {};
const currLocation = window.location.href,
parArr = currLocation.split("?")[1].split("&");
for (let i = 0; i < parArr.length; i++) {
const parr = parArr[i].split("=");
url_parameter[parr[0]] = parr[1];
}
However, if you use react-router you might want to go the the resource. Than the link would look like this:
http://www.example.com/john
In this case react allows to get the resource in the this.props.params: Here how to specify the route:
<Route path="/:name" component={Name}>
Here how to access the name in the component 'Name':
....
render() {
const {name} = this.props.params;
...
}
I hope this helps.
Upvotes: 3