react-router-dom v6 TypeScript withRouter for class components

Viewed 2410

I'm trying to update react-router-dom to v6 in my TypeScript React app.

In the offical react-router-dom documentation is simply states:

Along with the upgrade to v5.1, you should replace any usage of withRouter with hooks.

It completely ignore class components!

I searched for a long time on the internet, but all the articles I found

  • speak about JavaScript rather than TypeScript, or
  • speak about function components, or
  • refer to v5 (or lower) of react-router-dom since they speak about withRouter.

Is there a well documented way to upgrade react-router-dom to v6 in a TypeScripp React app which doesn't require to refactor all class components into function components?

1 Answers

Maybe not well documented, but this thread on GitHub may give you the right direction to make this work. User mjackson suggests wrapping your class components in a HOC so you can wire the withRouter hook and your class components together.

// in hocs.js
function withNavigation(Component) {
  return props => <Component {...props} navigate={useNavigate()} />;
}

function withParams(Component) {
  return props => <Component {...props} params={useParams()} />;
}

// in BlogPost.js
class BlogPost extends React.Component {
  render() {
    let { id } = this.props.params;
    // ...
  }
}

export default withParams(BlogPost);
Related