Passing an object as prop in React-router Link

17,947

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.

Share:
17,947
Prajwal
Author by

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, 2022

Comments

  • Prajwal
    Prajwal almost 2 years

    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
    Prajwal about 6 years
    Yea, was thinking about the same. But is it possible to pass an object as prop to another component tru Link?
  • Prajwal
    Prajwal about 6 years
    Yes, I was able to do it the same way now. Although I think getting from redux would be neater.
  • Prajwal
    Prajwal about 6 years
    browserHistory is not there in React-router-v4
  • Sergii Vorobei
    Sergii Vorobei about 6 years
    Yes, now it is a separate module, you need to include it reacttraining.com/react-router/web/api/Router