Skip to content Skip to sidebar Skip to footer

Passing An Object As Prop In React-router Link

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 pr

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.

Solution 3:

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.

Post a Comment for "Passing An Object As Prop In React-router Link"