I am currently working on integrating React in to a TypeScript based framework. Unfortunately as soon as I want to inject components, the typings are not correct anymore.
I know that this is not the way a lot of people are using React, but instead of using higher order components we want to use dependency injection as it is in our opinion the better pattern.
I have tried to do the following
import * as React from "react";
import * as ReactDOM from "react-dom";
export class Foo extends React.Component {
public render() {
return (<div>Bar</div>);
}
}
export class Foobar {
constructor(private component: Foo) {}
public render(): void {
const Component = this.component;
ReactDOM.render(
<Component />, // <Foo /> works perfectly
document.querySelector("#root")
);
}
}
But this does not work unfortunately. It errors with the following output
ERROR in src/app/test.tsx(17,14): error TS2604: JSX element type 'Component' does not have any construct or call signatures.
If I try it like this
public render(): void {
ReactDOM.render(
React.createElement(this.component, {}),
document.querySelector("#root")
);
}
It results in to the following
ERROR in src/app/test.tsx(15,33): error TS2345: Argument of type 'Foo' is not assignable to parameter of type 'string | StatelessComponent<{}> | ComponentClass<{}, any>'.
Type 'Foo' is not assignable to type 'ComponentClass<{}, any>'.
Type 'Foo' provides no match for the signature 'new (props: {}, context?: any): Component<{}, any, any>'.
I am not really in favor of using as any in this scenario as I would love to be able to refactor Foo without having to manually check every instance if the props are passed down correctly.
I have heard from React.sfc but as far as I can tell it doesn't fix the problem I am facing.
Foobut passing the class itself, it seems thatComponentClass<Props>would be the type you want to use