Search code examples
reactjstypescriptreact-router-dom

Properly typed withRouter - React router v6


I am trying to upgrade to react-router-v6 and I have a lot of class components which I do not want to convert to functional. I found a function from react-router which lets me use withRouter with class components however its not typed. Can someone help me out with this?

Source: https://reactrouter.com/en/main/start/faq#what-happened-to-withrouter-i-need-it

This is what I have:

import { useLocation, useNavigate, useParams } from "react-router-dom";

function withRouter(Component: any) {
  function ComponentWithRouterProp(props: any) {
    const location = useLocation();
    const navigate = useNavigate();
    const params = useParams();
    return <Component {...props} router={{ location, navigate, params }} />;
  }

  return ComponentWithRouterProp;
}

export default withRouter;

Thanks.


Solution

  • This should do the job, here is codepen.

    import { useLocation, useNavigate, useParams } from "react-router-dom";
    
    type IComponentWithRouterProp = {
      [x: string]: any;
    };
    
    export function withRouter(Component: Function): Function {
      function ComponentWithRouterProp(
        props: IComponentWithRouterProp
      ): JSX.Element {
        let location = useLocation();
        let navigate = useNavigate();
        let params = useParams();
        return <Component {...props} router={{ location, navigate, params }} />;
      }
    
      return ComponentWithRouterProp;
    }