michael tetteh
michael tetteh

Reputation: 13

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

                      `

Upvotes: 1

Views: 3777

Answers (3)

Hasan
Hasan

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

Upvotes: 0

Matiiv Vasyl
Matiiv Vasyl

Reputation: 127

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

Upvotes: 0

Nisar Akbar
Nisar Akbar

Reputation: 21

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

Upvotes: 2

Related Questions