-1

In my react code I am facing difficulty. I want to print product name based on its id ,where the product will be fetched from product.js. I am using router to show different products without reloading.

import product from './product'

export default function ProductScreen({match}) {
    const products=product.find(p=>p._id === match.params.id)
    return (
        <div>
            {products.name}
        </div>
    )
}

The console shows
Uncaught TypeError: Cannot read properties of undefined (reading 'params') at ProductScreen The code for router is

<Router>
          <Routes>
          <Route path="/" element={<HomeScreen />} exact/>
          <Route path="/product/:id" element={<ProductScreen />} />
        </Routes>
    </Router>

And product file is

const product=[
    {
        _id:'1',
        name : 'Shoes',
        images : '/img/shoe4.jfif',
        discription : 'Lorem10j,jdscjscjc nxkd kdn ddksad asdkjdhsadb'
    }
]

2 Answers2

0

You can use useParams()

import { useParams } from "@reach/router"

// route: /user/:userName
const User = () => {
  const params = useParams();

  return <h1>{params.userName}</h1>
)

from: https://reach.tech/router/api/useParams

Balkan
  • 21
  • 2
0

you can get query param in productScreen.js:

import {useRouter} from 'react-router-dom'
const {id} = useRouter();
const [data , setData] = useState({});
useEffect(() => {
  if(id){
     const products=product.filter(p=>p._id == id);
      setData(products);
   }
},[id])
    return (
    <div>
        {data?.name}
    </div>
Paiman Rasoli
  • 1,088
  • 1
  • 5
  • 15