In order to not rebuild everything from class components to functional components I need to use the wrapper from the React Router Documentation:
import {
useLocation,
useNavigate,
useParams,
} from "react-router-dom";
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
return ComponentWithRouterProp;
}
However I need to correct types for Component and props in Typescript. (A quick test with any shows it works). But what are the correct types that I need to use?
This is what I tried, give Component the Function type but still not sure with props as I want to avoid to use any..
import { useLocation, useNavigate, useParams } from "react-router-dom";
type IComponentWithRouterProp = {
[x: string]: any;
};
function withRouter(Component: Function) {
function ComponentWithRouterProp(props: IComponentWithRouterProp) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return <Component {...props} router={{ location, navigate, params }} />;
}
return ComponentWithRouterProp;
}
export default withRouter;
EDIT:
So I found out that what I am looking for is React.ComponentType, which is a union of ComponentClass and ComponentFunction.
But when I use Component: React.ComponentType then TS throws an error at my router in the return - router={{ location, navigate, params }}
Type '{ router: { location: Location; navigate: NavigateFunction; params: Readonly<Params<string>>; }; }' is not assignable to type 'IntrinsicAttributes'.
Property 'router' does not exist on type 'IntrinsicAttributes'.
So this throws a new error, how can I solve this?