9

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.

Prajwal
  • 3,930
  • 5
  • 24
  • 50

3 Answers3

14

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

Dyo
  • 4,429
  • 1
  • 15
  • 30
  • 2
    Yes, I was able to do it the same way now. Although I think getting from `redux` would be neater. – Prajwal Feb 23 '18 at 14:17
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.

Dev
  • 3,922
  • 3
  • 24
  • 44
  • Yea, was thinking about the same. But is it possible to pass an object as prop to another component tru `Link`? – Prajwal Feb 23 '18 at 14:07
0

You can try to do it through query params as in Pass object through Link in react router, which is quite ugly.

Also you can try to replace Link with some other element, e.g. button and in click listener do location change via browserHistory.push({ pathname:"/product/" + this.props.product.Id, state: this.props.product}) and and product as state property.

Sergii Vorobei
  • 1,477
  • 13
  • 19