react-router-dom with typescript triggering error ts(2786)

Viewed 29

I am working on a SPA totally written in react and typescript and I had to develop an helper that injects the location, navigate and params props because in the new versions of react-router-dom the helper withRouter do not longer exits so i built my own one.

This is my withRouter function helper:

import React from 'react';
import {
 NavigateFunction, useLocation, useNavigate, useParams,
} from 'react-router-dom';

declare type LocationState = {
    hash: string;
    key: string;
    pathname: string;
    search: string;
    state: IBDAffiliatiObject;
};

export interface IRoutedProps<Params = IBDAffiliatiObject, State = LocationState> {
    location: State;
    navigate: NavigateFunction;
    params: Params;
}

export function withRouter<P extends IRoutedProps>(Child: React.ComponentClass<P>) {
    return function (props: Omit<P, keyof IRoutedProps>): JSX.Element {
        const location = useLocation();
        const navigate = useNavigate();
        const params = useParams();
        return (
            <Child {...props as P} location={location} navigate={navigate} params={params} />
        );
    };
}

actually my project builds correctly, but the tslinter is triggering this error that I don't clearly understand:

'Child' cannot be used as a JSX component. Its instance type 'Component<P, any, any>' is not a valid JSX element. The types returned by 'render()' are incompatible between these types. Type 'React.ReactNode' is not assignable to type 'import("D:/progs/BuffettiAffiliati/BD.Affiliati.Client/bdaffiliaticlient/node_modules/@typ>es/react-lazy-load-image-component/node_modules/@types/react/index").ReactNode'. Type '{}' is not assignable to type 'ReactNode'.ts(2786)

Furthermore I don't really what that is .../node_modules/@types/react-lazy-load-image-component/node_modules/@types/react/index about

Has anyone else encountered this problem? How could it be fixed? Thanks

1 Answers

SOLVED

just updating react, react-dom, @types/react, @types/react-dom to their last version.

{
    "@types/react": "^18.0.20",
    "@types/react-dom": "^18.0.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
}
Related