React router, transfer details using Link

I use React Router to navigate to a page in my application as follows:

<Link to={`/single/${this.props.data.pageId}`} params={{singleId: 1}}>GotoPage!</Link> 

This works fine, but I would also like to pass an additional property to a new page.

When rendering a component without using a link, I would do something like:

 <MyComponent myProp={this.props.data}/> 

I tried to skip myProp={this.props.data} in options like this:

 <Link to={`/single/${this.props.data.pageId}`} params={{singleId: 1, myProp={this.props.data}}}>GotoPage!</Link> 

But it does not work, since myProp undefined on the new page opposes the page to which I can get:

 this.props.params.pageId; 

Shouldn't I pass non-route parameters using Link ?

+5
source share
2 answers

In the documentation for Link , as well as the source, there is no mention of this with param . But I get what you are trying to do.

Instead of hard-coding routes, I can recommend using the router.push() event-routing history function. Do something like this:

 class Foo extends React.Component { ... const handleNewRoute = () => { let { pageId } = this.props.data let singleId = '1' this.context.router.push({ // use push pathname: `/single/${pageId}`, query: { singleId } }) } render() { return ( <button onLeftClick={this.handleNewRoute} /> ) } } 

By the way, in React / JSX something like ...{{singleId: 1, myProp={this.props.data}}}... should be <Link...foobar={{singleId: 1, myProp: this.props.data}}> . The first syntax is incorrect.

+2
source

I think the best way to get additional data is ajax.

But if you want your way to do this, I check the api of the link and I find the request property.

 query: An object of key:value pairs to be stringified. 

so that you can use this to pass the key object: value to the next route, but this object will be stiffened and passed, although, in my opinion, url. I prefer ajax for this.

+1
source

Source: https://habr.com/ru/post/1243025/


All Articles