React-router-v6 access a url parameter

Issue

In react-router-dom v6 the Route components no longer have route props (history, location, and match), and the current solution is to use the React hooks “versions” of these to use within the components being rendered. React hooks can’t be used in class components though.

To access the match params with a class component you must either convert to a function component, or roll your own custom withRouter Higher Order Component to inject the “route props” like the withRouter HOC from react-router-dom v5.x did.

Solution

I won’t cover converting a class component to function component. Here’s an example custom withRouter HOC:

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

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

And decorate the component with the new HOC.

export default withRouter(Post);

This will inject a params prop for the class component.

this.props.params.id

Leave a Comment