简体   繁体   中英

ReactJSA Typescript Route JSX Element is not accepting

Good day everyone, I am new to ReactJS/Typescript and need some tips with below behavior. I want to restrict access to Dashboard component with below codes:

const DashBoard = () => {
    return (
        <h1> DashBoard </h1 >
    )
}
export default DashBoard;

Protecting route to DashBoard component by using in other component NavBar:

....
<PrivateRoute path="/dashboard" component={DashBoard} exact isAuth={true} />
...

Below is PrivateRoute:

import React from "react";
import { Route, Redirect } from "react-router-dom";

interface PrivateRouteProps {
    path: string;
    exact: boolean;
    component: JSX.Element; //using component: React.FC works
    isAuth: boolean;
}
const PrivateRoute = (props: PrivateRouteProps) => {

    return props.isAuth ? (<Route path={props.path} exact={props.exact} component={props.component} />) :
        (<Redirect to="/login" />);
};
export default PrivateRoute;

However, I got below error:

Type '() => Element' is missing the following properties from type 'ReactElement<any, any>': type, props, key

My questions:

Using "component: React.FC" or "component: any" will get above error gone but is this safe as I am returning JSX.Element in all components as per https://github.com/typescript-cheatsheets/react

Thank you

Using component: React.FC is indeed the right approach.

This will handle your generic types, the default prop types (like children) and the return types of your components' function(as JSX elements).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM