Angel Martinez
Angel Martinez

Reputation: 504

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?

Upvotes: 0

Views: 1213

Answers (1)

mantiksizinsan
mantiksizinsan

Reputation: 89

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

Upvotes: 1

Related Questions