React – TypeError: Cannot read properties of undefined (reading ‘params’)

The tutorial appears to be older and using react-router-dom version 5 whereas you are using version 6. In version 6 there were many breaking API changes. The Route components no longer use component or render props, the element prop that is passed a valid JSX literal replaced them. route props (history, location, and match) also no longer exist, the routed components must use the React hooks to access them now.

Routes and Route

interface RouteProps {
  caseSensitive?: boolean;
  children?: React.ReactNode;
  element?: React.ReactElement | null;
  index?: boolean;
  path?: string;
}

Given route: <Route path="/product/:id" element={<ProductScreen/>} />

Use the useParams hook to access the id match param. The match param will be a string, so if your product ids are a number type, then to ensure strict equality convert the _id property to a string to use a type-safe comparison. Don’t forget that Array.prototype.find returns undefined if no match is found, so the code should check the result value prior to attempting to access into it for properties when rendering.

import { Link, useParams } from 'react-router-dom';
...

function ProductScreen() {
  const { id } = useParams();
  const product = products.find((p) => String(p._id) === id);

  if (!product) return null; // or fallback UI

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

Leave a Comment