Im using React Router to navigate to a page in my app like this:
<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 the new page.
When rendering a component without using Link I would do something like:
<MyComponent myProp={this.props.data}/>
I have tried passing myProp={this.props.data}
along in params like this:
<Link to={`/single/${this.props.data.pageId}`} params={{singleId: 1, myProp={this.props.data}}}>GotoPage!</Link>
But it does not seem to work as myProp is undefined on the new page as oppose to pageId which I can get like:
this.props.params.pageId;
Am I not supposed to be able to pass non-route related parameters with Link
?
In the documentation for Link
and also the source, there's no mention of it taking param
. But I get what you're trying to do.
Instead of hard-coding routes, may I recommend using react-router's history function router.push()
. Do something like this instead:
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 former syntax is wrong.
I think the better way to get the additional data is an ajax.
But if you want your way to do this,I check the api of Link and I find a query property.
query:
An object of key:value pairs to be stringified.
so you can use this to pass a object of key:value to the next route,but this object will be stringified and passed though the url I think.I prefer an ajax for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With