When a product in the list is clicked, we want to open the single product page.
How do we do so?
We add a click handler to the container div that holds the product card in the list:
import React from 'react'
export default props => {
const deleteProduct = index => {
props.deleteProduct(index)
}
return (
<div className="products-list">
{props.products
? props.products.map((value, index) => {
return (
<div
key={index}
onClick={() => props.history.push('/product/' + value.slug)}
>
<img src={value.image} />
<h2>{value.name}</h2>
<p className="description">{value.description}</p>
<p className="price">${value.price}</p>
<button onClick={() => deleteProduct(index)}>ⓧ</button>
</div>
)
})
: 'No products'}
</div>
)
}
using the history
prop, like we did before. In App.js we must pass it to ProductsList
:
<Route
exact
path="/"
render={({ history }) => (
<ProductsList
products={products}
deleteProduct={deleteProduct}
history={history}
/>
)}
/>
That’s it! Now when clicking a product the URL changes and we are shown that product page.
That page is empty though! We need to fill it. Open the src/components/SingleProduct.js
file, and let’s add a template similar to the one we added to ProductsList
, this time focused on a single product. We’ll get the products details in a product
prop.
We must populate this prop based on the slug we see in the URL. This in done inline, in the App component JSX:
<Route
path="/product/:slug"
render={({ match }) => (
<SingleProduct
product={products.find(p => p.slug === match.params.slug)}
/>
)}
/>
Once this is done, we can show the product data in the template:
import React from 'react'
export default props => {
return (
<div className="single-product">
<img src={props.product.image} />
<h2>{props.product.name}</h2>
<p className="description">{props.product.description}</p>
<p className="price">${props.product.price}</p>
</div>
)
}