2
votes

I am trying to dynamically import a React Component from a module like this:

state: {
  OsdComponent: React.Component<any, any>
}

constructor(props) {
  super(props)
  this.state = {
    OsdComponent: null,
  }
}

async componentWillMount() {
   const {OsdComponent} = await import(`manifest-viewer`)
   this.setState({OsdComponent})
}

and then try to use it like this in render:

render() {
   const {OsdComponent} = this.state
   if (OsdComponent) {
     <OsdComponent/>
   }
}

but Typescript compile fails with 'TS2604: JSX element type 'OsdComponent' does not have any construct or call signatures.'

The code works in another module that is not compiled with Typescript.

1
The state type of the component class containing the methods you quoted is probably wrong. Please add the declaration of that class to the question (e.g., class MyComponent extends React.Component<..., ...>). - Matt McCutchen
Note that I wasn't notified when you edited the question, so it was just lucky that I checked back today and saw the edit. When someone asks you for more information and you add it to the question, it's best to add a comment to notify them. - Matt McCutchen

1 Answers

3
votes

In the <Foo .../> syntax, Foo must be a component type (i.e., of type React.ComponentType<P> for the appropriate P); for example, Foo could be the name of a component class you defined. React will create an instance of the component type for you during rendering. You would not pass in a component instance you created yourself (e.g., let Bar = new Foo(); <Bar .../>); that would not make sense. But that is what it appears you are trying to do with OsdComponent, since you have declared its type as React.Component<any, any>. Change the type to React.ComponentType<any, any> (which is probably what your dynamic import actually returns) and the error should go away. (Of course, it would be better to specify at least the props type instead of using any.)