Passing an object as prop in React-router Link
Solution 1
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
Solution 2
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.
Prajwal
I spend most of my time in front-end development. Mostly because it's something very close to the user. It gives me an opportunity to be in user's shoes and find a solution for their problems. I also spend time on exploring new technologies, software, books, and coffee shops.
Updated on June 14, 2022Comments
-
Prajwal almost 2 years
I'm getting the list of products in
ProductList
, in which, I need to pass the selected product object toProduct
.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 fromProductList
toProduct
.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.
-
Pass props in Link react-router
<--- this is similar to my issue, but answer doesn't work for react-router v4
- react-router - pass props to handler component
- React: passing in properties
-
Pass props in Link react-router
-
Prajwal about 6 yearsYea, was thinking about the same. But is it possible to pass an object as prop to another component tru
Link
? -
Prajwal about 6 yearsYes, I was able to do it the same way now. Although I think getting from
redux
would be neater. -
Prajwal about 6 years
browserHistory
is not there inReact-router-v4
-
Sergii Vorobei about 6 yearsYes, now it is a separate module, you need to include it reacttraining.com/react-router/web/api/Router