3

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?

1

1 Answer 1

3

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.