How to pass params into link using React router v6?

Issue(s)

  1. react-router-dom v6 Route components rendered via the element prop don’t receive route props.
  2. Route children components must use react hooks to access the route context, i.e. useParams, useLocation, useNavigate, etc… and therefore must be function components.
  3. There no longer exists a withRouter Higher Order Component.

Solution

DetailsPage is a class-based component so I see a couple options for getting access to the route’s match params.

  1. Convert DetailsPage to be a function component and use the useParams react hook.
  2. Write your own withRouter HOC to access the route context and pass as props any of the react-hook accessible values.

I won’t cover converting a class-based component to a function component, but can provide a simple HOC solution to pass to DetailsPage (or any other class-based component) the match params.

const withRouter = WrappedComponent => props => {
  const params = useParams();
  // etc... other react-router-dom v6 hooks

  return (
    <WrappedComponent
      {...props}
      params={params}
      // etc...
    />
  );
};

You can now wrap & export your class-based components in the very familiar way they were from v4/v5.

v6 api-reference

Leave a Comment