Ernesto
Ernesto

Reputation: 301

React Class behaviour with "this" keyword

Why do I need to add bind(this) for handleChange in the onChange handler to have the proper this keyword?

class SearchBar extends React.Component{
  constructor(props){
    super(props);
  }
  handleChange(){
    console.log(this)
    this.props.onUserInput(
      this.refs.filterTextInput.value,
      this.refs.inStockOnlyInput.checked
    );
  }
  render() {
    return (
      <form>
        <input
          type="text"
          placeholder="Searrch...." 
          value={this.props.filterText}
          ref="filterTextInput"
          onChange={this.handleChange.bind(this)} // the bind(this) is needed if not this in handleChange became undefined
        />
        <p>
          <input
            type="checkbox"
            checked={this.props.inStockOnly}
            ref="inStockOnlyInput"
            onChange={this.handleChange}
          />
          {' '}
          only show products in stock
        </p>
      </form>
    );
  }
}

Upvotes: 4

Views: 692

Answers (1)

rob0rt
rob0rt

Reputation: 479

It's because with the new React extends Component syntax, they removed autobinding for this on component creation like they had in the old .createClass syntax. By default, with the class syntax in es2015, you have to bind this to a method in order to use the class this, so the same holds here.

You can read about React's decision to make this change in this changelog blog post.

Upvotes: 4

Related Questions