Reputation: 4054
I have used router for routing. There is a list of product and when a product is clicked, a detail page of that product should be shown(product.name, product.price). I tried passing product object in query but it is not working that way.
Here is my code
productGrid.js
const product = _.map(products, (product) =>
<Col xs={12} md={4} key={product.id} className="products">
<div className="product">
<Link to={{pathname: `product/${product.name}`, query: { query: product }}}>
<img src={product.image} className="img-responsive" />
</Link>
<span className="pull-left product-name">{product.name}</span>
<span className="pull-right price">${product.price}</span>
</div>
</Col>
);
product-view.js
class ProductView extends React.Component {
render() {
console.log('product', this.props.location.query);
return (
<div>Product View</div>
);
}
}
this.props.location.query consoles
Upvotes: 2
Views: 8164
Reputation: 21864
I would suggest you to pass the list of products as props
to ProductView
then to retrieve the product with its id
. This way there is no downside when a user navigates directly to the product.
productGrid.js
<Link to={{pathname: `product/${product.name}`, query: { id: product.id }}}>
product-view.js
class ProductView extends React.Component {
render() {
const { products, location } = this.props;
if (!products.length || !location) {
return (<div>Loading...</div>);
}
const product = products.find(p => p.id == location.query.id);
return product ? (
<div>
<h1>{product.name}</h1>
<img src={product.image} />
<p>{product.price}</p>
</div>
) : (
<div>Error: Product doesn't exist</div>
);
}
}
Upvotes: 4
Reputation: 36807
They query
object of a location descriptor will be turned into a query string. You can use the state
property of a location descriptor to pass state between views.
<Link to={{ pathname: `product/${product.name}`, state: { product } }}>
Then, in your product component, you can check this.props.location.state
to get the associated data. The downside to this is that a user that navigates directly to the same URL will not have the state
available to them.
Upvotes: 1