When I pass in some Components to a Route Component I get a TS compiler error:
Type '{ main: typeof MainComponent; sidebar: typeof SidebarComponent; }' is not assignable to type 'RouteComponents'. Property 'sidebar' is incompatible with index signature. Type 'typeof SidebarComponent' is not assignable to type 'ReactType'. Type 'typeof SidebarComponent' is not assignable to type 'StatelessComponent'. Type 'typeof SidebarComponent' provides no match for the signature '(props: any, context?: any): ReactElement'
I've tried to correctly construct a RouteComponents object, but I had to modify the react-router's index.d.ts to export the RouteComponents definition as only RouteComponent is exported, and it still didn't like the expression. Where can I find out what a RouteComponents object supposed to look like?
Here is the simple file routes.tsx:
import * as React from 'react'
import { IndexRoute, Route } from 'react-router'
import App from './components/App'
import MainComponent from './components/MainComponent'
import OtherMainComponent from './components/OtherMainComponent'
import SidebarComponent from './components/SidebarComponent'
const routes = () => {
return (
<Route path="/" component={App}>
<IndexRoute components={{ main: MainComponent, sidebar: SidebarComponent }} />
<Route path="/add" components={{ main: OtherMainComponent, sidebar: SidebarComponent }} />
</Route>
)
}
export default routes
As I mentioned, I tried it the following way too:
const indexRouteComponents: RouteComponents = {
main: MainComponent,
sidebar: SidebarComponent
}
const routes = () => {
return (
<Route path="/" component={App}>
<IndexRoute components={indexRouteComponents} />
<Route path="/add" components={{ main: OtherMainComponent, sidebar: SidebarComponent }} />
</Route>
)
}
The components={indexRouteComponents} part does not have an error, but creating the indexRouteComponents object is an error (The same error as above, because it's not a correct RouteComponents object)
What is the correct way to set up the react-router Components using Typescript?
Edit: here are Github issues related to this: https://github.com/ReactTraining/react-router/issues/4317 https://github.com/DefinitelyTyped/DefinitelyTyped/issues/13689
const AppRouter = [
{
main: MainComponent,
exact: true,
path: "/",
sidebar: SidebarComponent,
},
{
main: OtherMainComponent,
exact: true,
path: "/add",
sidebar: SidebarComponent,
}
];
And in your main component:
public render() {
return (
<Router>
<div className={"sidebar"}>
{AppRouter.map((route, index) => (
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.sidebar}
/>
))}
</div>
<div className={"content"}>
{AppRouter.map((route, index) => (
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.main}
/>
))}
</div>
</Router>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With