React event handlers with Typescript and JSX React event handlers with Typescript and JSX typescript typescript

React event handlers with Typescript and JSX


You have to bind methods with this because you don't use React.createClass that does it automatically.Example with a class syntax:

class Counter extends React.Component {  constructor() {    super();    this.handleChange = this.handleChange.bind(this);    this.handleClick = this.handleClick.bind(this);  }  handleChange() {    ...  }  handleClick() {    ...  }}


You must change your render method:

render() {    // ...        <button onClick={this.handleClick.bind(this)}>Like</button>        <input value={this.state.name} onChange={this.handleChange.bind(this)} />    // ...}

Since you're calling an event, the this keyword will be changed to the event's default context.By using .bind(this) you ensure that the context being called will be the instance of your class.


Another method is to use fat arrow functions for event handlers which get automatic "this" binding.

 handleClick = (evt, domNode):void => {     this.setState({ liked: !this.state.liked, name: this.state.name }); }; <button onClick={() => this.handleClick()}>Like</button>