5

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
  • You are correct, RRDv6 no longer exports a withRouter HOC. You can either convert your components to function components or create a custom withRouter HOC using the v6 hooks and injects the "route props" into the decorated components. Commented Nov 30, 2021 at 17:01

1 Answer 1

0

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Can you explain how to do it in Typescript?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.