2
votes

I am using typescript with react I wanted to render a component but getting typescript error

Type '(props: RouteProps) => JSX.Element' is not assignable to type 'PropsWithChildren'.
Property 'component' is missing in type '(props: RouteProps) => JSX.Element' but required in type 'RouteProps'.

 import React, { ReactNode, PropsWithChildren } from "react";
 import { Route, Redirect } from "react-router";
 
  export interface RouteProps {
     component: FunctionComponent;
   }


 interface PrivateRoutesProp {
   // component: PropsWithChildren<RouteProps> // not works  
     // also having "noImplicitAny": true, [this was mandatory]
   component: PropsWithChildren<???>; //what i have to use here,object is not working
   exact: boolean;
  path: string;
 }

const PrivateRoute = ({ component: Component, ...rest }: PrivateRoutesProp) => (
  <Route
   {...rest}
  render={(props) => (isLoggedIn ? <Component {...props} /> : <Redirect to="/" />)}
  />
  );

 export default PrivateRoute;

can anyone help me out of this

1

1 Answers

0
votes

PropsWithChildren just type PropsWithChildren<P> = P & { children?: ReactNode }; It should include props of Route and custom props.

Here my idea:

export interface PrivateRoutesProp {
    component: FunctionComponent;
    exact: boolean;
    path: string;
    isLogin: boolean
}

const PrivateRoute = ({ component, isLogin, ...rest }: PropsWithChildren<PrivateRoutesProp & RouteProps>) => (
    <Route
        {...rest}
        render={(props) => (isLogin ? React.createElement(component, props) : <Redirect to="/" />)}
    />
);