1

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

                      `
  • Does this answer your question? [Pass props in Link react-router](https://stackoverflow.com/questions/30115324/pass-props-in-link-react-router) – Mellet Feb 17 '21 at 16:48

3 Answers3

2

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();
0

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 page
const {id} = useParams()

Matiiv Vasyl
  • 117
  • 3
0

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/>
     </>
    )