Search code examples
reactjstypescripttsx

React.render in TypeScript for component with both props and state


I have a TypeScript TSX file with a React component like this:

interface IHiProps {
  a: string;
  b: string;
}

interface IHiState {

}

class Hi extends __React.Component<IHiProps, IHiState> {
  // render…
}

How do I correctly render this component in TypeScript?

var hiComponent: __React.Component<IHiProps, IHiState>;
hiComponent = __React.render(__React.createElement(Hi), { a: "A", b: "B" }, document.body);

This fails me with Argument of type 'typeof Hi' is not assignable to parameter of type 'ComponentClass'. I am using definitely typed files from the DefinitelyTyped repository of Boris Yankov.


Solution

  • Does it work when you change your class like this?

    class Hi extends __React.Component<IHiProps, IHiState> {
      static propTypes: __React.ValidationMap<any> = {
        a: __React.PropTypes.string,
        b: __React.PropTypes.string
      }
    
      // render…
    }
    

    Also using __React is suspicious as it is internal variable of React.d.ts. In runtime there would not be such variable - if you would not create it. Consider rather using modules:

    /// <reference path="/path/to/react.d.ts" />
    import * as React from React;