'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?

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 1:[1]

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;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Damian Busz