简体   繁体   中英

Dynamic Routes: React/TypeScript

I'm converting a React/JavaScript project into a React/TypeScript. I'm using react-router-dom to handle all of the routing stuff. So, I have a file called routes/index.js (Yes, a JavaScript file) and inside of this file you will find something like this:

import { lazy } from 'react'

// use lazy for better code splitting, a.k.a. load faster
const Dashboard = lazy(() => import('../pages/Dashboard'))

const routes = [
  {
    path: '/dashboard', // the url
    component: Dashboard, // view rendered
  },
]

export default routes

In another file, that helpme to load the routes, I have the following code:

<Switch>
  {routes.map((route, i) => {
    return route.component ? (
      <Route
        key={i}
        exact={true}
        path={`/app${route.path}`}
        render={(props) => <route.component {...props} />}
      />
    ) : null;
  })}
  <Redirect exact from="/app" to="/app/dashboard" />
  <Route component={Page404} />
</Switch>;

The problem is the <route.component {...props}/> , TypeScript give me this error:

Type '{ history: History; location: Location; match: match<{}>; staticContext?: StaticContext | undefined; }' has no properties in common with type 'IntrinsicAttributes'.

How I can fix this problem?

As far as I know, you are getting this error because of using a lowercase component name. So, you can use something like this:

const Component = route.component as React.ComponentType;
...
return <Component {...someProps} />

you can also provide some generic types for this React.ComponentType

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