I am developing an Ecommerce project, I managed to create a product grid and link to an route to the specific product, but i am unable to see the data of the item. My products code is here
const Container = styled.div`
padding: 20px;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
`
const Products = () =>{
return (
<Container>
{products.map(item=>(
<Product item={item} key={item.id}/>
))}
</Container>
)
}
export default Products;
My product code is here
const Product = ({item}:any) => {
return (
<Container >
<Link to={"/productDetail/" + item.id}>
<img src={item.image} className='imag'/>
</Link>
<Box justifyContent='center' display='flex'>
<Typography>
{item.name}
</Typography>
</Box>
<Box justifyContent='center' display='flex'>
<Typography>
{item.price}
</Typography>
</Box>
<Box justifyContent='center' className='display' >
<Button className='btn'>Buy</Button>
</Box>
</Container>
)
}
export default Product;
And here is my attempt to create a single product page
function ProductDetail() {
let { id } = useParams<{ id: string }>();
return (
<div>
<img src={item.image} className='imag' />
</div>
)
}
export default ProductDetail;
And my route on the home page is like this:
<Route exact path="/productDetail/:id" >
< ProductDetail />
</Route>
You are not seeing data because item is undefined. If you want to pass data to ProductDetail using navigation then try add state to the Link and use inside the <ProductDetail />
// product-grid page
<Link to="path_to_product_detail" state={item}>...</Link>
Now inside <ProductDetail /> import useLocation method from react router dom which will contain data that is added to the state prop of link component.
//product-detail page
const location = useLocation() // import from react-router-dom
const item = location.state
However, This is not the good practice for your use case, because in the product grid page you will fetch only few details like title, thumbnail & id. But in the product description you have to fetch everything about the product which you may not called while in product grid page. The best way is to populate the detailed data, item in our case with api.