'React : show specific product data when user clicks on one product in the market place
i have fetched the data from an api and successfully displayed the data in a marketplace. Now when a user clicks on one product it should open the product details page and send the data of that product to populate the details page. i want to pass the specific data of one product from the Api to the product details page when that product is clicked. Please help
this is the code to render the various products
const renderitems = currentitems.map((item) => {
return <div key={item.id} className="col-md-6">
<div className="listing">
<div className="listing-thumbnail">
<Link to="/listing-details-v1"><img src={ item.images[0]} alt="listing" /></Link>
how do i pass the id of the clicked on link to the details page
`
Solution 1:[1]
it's so simple. you'll pass product id as a parameter in the route and will get product id on the product detail page.
Step 1: Register route like
<Route path="/listing-details-v1/:id" ..... />
Step 2: Link like
<Link to={"/listing-details-v1/" + item.id}><img src={ item.images[0]} alt="listing" /></Link>
Step 3: get parameter on product detail page component like
import { useParams } from "react-router-dom";
let { id } = useParams();
Solution 2:[2]
You can create Route with dynamic params
<Route path="listing-details-v1/:id" ... />
Then pass params with link
<Link to={`/listing-details-v1/${item.id}`}></Link>
And then you can catch it with useParams hook in your details pageconst {id} = useParams()
Solution 3:[3]
In the "listing-details-v1" page, you can declare an useState. Then using useEffect, you can map the "currentitems" to get the "item" id and inside "if" condition, if item.id matches the "id" destructured from useParams, setState the "item".
const details, setDetails = useState([]);
const {id} = useParams(); //import from react-router-dom
useEffect(() => {
const getDetails = currentitems.map((item) => {
if (item.id === id) {
return setDetails(item);
}
});
}, [id]);
return (
<>
<h1>{details.title}<h1/>
</>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nisar Akbar |
| Solution 2 | |
| Solution 3 | Hasan Sharif |
