Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I match a params in React Router v6?

I have been trying to display the product name in the ProductScreen component by passing the ID of the image.

My router configuration looks like this:

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route>
      <Route path='/' element={<HomeScreen />} exact />
      <Route path='/cart' element={<ProductScreen />} />
      <Route path='/product/:id' element={<ProductScreen />} />
    </Route>
  )
)

The id is then used to retrieve the product name from product.js
This is to be displayed inside the productscreen.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import products from '../products'

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

How do I do this?

>Solution :

react-router-dom@6 removed route props, use the useParams hook in the routed component.

Be aware also that Array.prototype.find does return undefined if/when no element in the array is matched. The UI could should check first that a result was found.

The route path parameters are always a string type, so you will also want to use a type-safe comparison to your data. I suggest converting and using string comparisons and use a strict equality check.

Example:

import { useParams } from 'react-router-dom';
import products from '../products';

function ProductScreen() {
  const { id } = useParams();

  const product = products.find((p) => String(p._id) === id);

  if (!product) {
    return <div>No product.</div>
  }

  return (
    <div>
      {product.name}
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading