I'm creating a page, like Amazon, and in the index page I have a list of some products, 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 stuff that I saw on the web.
CodePudding user response:
If you want to get the id as a prop you must forward it to the ProductScreen component.
Now if you want to grab it from the url, you could use the useParams hook from react-router-dom. Guide: https://v5.reactrouter.com/web/example/url-params
CodePudding user response:
Try doing so and see what you get.
import React from 'react';
import data from '../data';
import {useParams} from "react-router-dom"
function ProductScreen(props) {
const {id} = useParamas();
console.log(id)
return <div>Product Screen</div>
}
export default ProductScreen;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>