Reputation: 101
I'm creating a page, like Amazon. In the index page, I have a list of products, and when the user clicks the link it goes to the product page that has all the details of the product, but for me to create this page I've to get the ID from the product but I can't get it.
App.js:
<main className="main">
<div className="content">
<Routes>
<Route path="/product/:id" element={<ProductScreen />} />
<Route path="/" exact element={<HomeScreen />} />
</Routes>
</div>
</main>
HomeScreen:
import React from 'react';
import data from "../data";
import { Link } from 'react-router-dom';
function HomeScreen(props) {
return (
<ul className="products">
{
data.products.map(product =>
<li>
<div className="product">
<Link to={'/product/' + product._id}>
<img
src={product.image}
alt="Product"
className="product-image"
/>
</Link>
<div className="product-name">
<Link to={'/product/' + product._id}>{product.name}</Link>
</div>
<div className="product-brand">{product.brand}</div>
<div className="product-price">{product.price}</div>
<div className="product-rating">{product.rating} Leafs ({product.numberReviews} Reviews)</div>
</div>
</li>
)
}
</ul>
);
}
export default HomeScreen;
ProductScreen:
import React from 'react';
import data from '../data';
function ProductScreen(props) {
console.log(props.match.params.id)
return <div>Product Screen</div>
}
export default ProductScreen;
I console.log it to see if everything was okay but the error shown is
TypeError: Cannot read properties of undefined (reading 'params')
What am I missing? I tried several kinds of stuff that I saw on the web.
Upvotes: 3
Views: 3260
Reputation: 84
For those who got no result, try this:
import React from 'react';
import data from '../data';
import {useParams} from "react-router-dom"
function ProductScreen(props) {
const params = useParams();
const id = params.id
console.log(id)
return <div>Product Screen</div>
}
export default ProductScreen;
Upvotes: 0
Reputation: 46161
You need to use useParams
hook from React Router Dom. Like below:
import React from 'react';
import data from '../data';
import {useParams} from "react-router-dom"
function ProductScreen(props) {
const {id} = useParams();
console.log(id)
return <div>Product Screen</div>
}
export default ProductScreen;
After setting /product/:id
router as you did:
<Route path="/product/:id" element={<ProductScreen />} />
Upvotes: 2