ReactJS component written in Typescript

suggest change

You can use React components in TypeScript the same way as in Facebook’s example. Change the file extension from jsx to tsx:

//helloMessage.tsx:
var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});
ReactDOM.render(<HelloMessage name="John" />, mountNode);

To use TypeScript’s static checking, do two things:

1) Convert the React.createClass example to an ES6 class:

//helloMessage.tsx:
class HelloMessage extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}
ReactDOM.render(<HelloMessage name="John" />, mountNode);

2) Add props and state interfaces:

interface IHelloMessageProps {
    name:string;
}

interface IHelloMessageState {
  //empty in our case
}

class HelloMessage extends React.Component<IHelloMessageProps, IHelloMessageState> {
  constructor(props: IHelloMessageProps){
    super(props);
  }
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);

TypeScript then reports an error if a required prop is missing, or if a prop is passed that the interface does not define. React and ReactDOM must be in scope (globals or imports). The empty state interface is only there to fill the second type argument.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents