React, how to pass product id to details page with React Router Dom?

Viewed 330

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 stuff that I saw on the web.

1 Answers

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;
Related