I'm getting the list of products in ProductList
, in which, I need to pass the selected product object to Product
.
Currently, I'm trying pass the id
as a route param and get the product object again. But I want to send the entire product object from ProductList
to Product
.
My Route is
<Route path={joinPath(["/product", ":id?"])} component={Product} />
ProductList component Link
<Link to={"/product/" + this.props.product.Id} >{this.props.product.Name} </Link>
How to pass product object to Product
as a prop?
the below one throws error in Typescript saying the following property does not exist on Link
Type.
<Link to={"/product/" + this.props.product.Id} params={product}>{Name}</Link>
I tried the following questions, but none seems to have my issues.
<--- this is similar to my issue, but answer doesn't work for react-router v4
To recap, if you need to pass data from Link through to the new component that's being rendered, pass Link s a state prop with the data you want to pass through. Then, to access the Link s state property from the component that's being rendered, use the useLocation Hook to get access to location. state .
However, with React Router v6, since you're in charge of creating the element, you just pass a prop to the component as you normally would. Want to learn more? If you liked this post and want to learn more, check out our free Comprehensive Guide to React Router.
Use the spread syntax (...) to pass an object as props to a React component, e.g. <Person {... obj} /> . The spread syntax will unpack all of the properties of the object and pass them as props to the specified component.
You can't pass data to next/link component. Even if you would pass it, you won't be able to access it on server-side when a user visits the page directly or refreshes it.
The "to
" property of Link
can accept an object so you can pass your props like this :
<Link to={
{
pathname: "/product/" + this.props.product.Id,
myCustomProps: product
}
}>
{Name}
</Link>
Then you should be able to access them in this.props.location.myCustomProps
I would suggest using redux
for retrieving the data. When you navigate to product route you can get the product
details by dispatching some action.
componentDidMount() {
let productId = this.props.match.params.Id;
this.props.actions.getProduct(productId);
}
The product
route should be connected with the the store.
Hope this helps.
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