Dale Jefferson

Dale Jefferson

Father, Husband, Classical Liberal, Software Developer

Class properties with React

By Dale Jefferson. Published
JavaScript, React

Dealing with this binding in JavaScript can be a real pain. In this article, I will show you three ways to avoid binding issues. Class Properties is the new JavaScript syntax for creating handler functions that have the correct this binding.

Anonymous Arrow Functions

This creates a new function on every render potentially invalidating any efforts to memorise in Button.

class AwesomeProject extends Component {
  constructor() {
    super();

    this.state = {n: 0};
  }

  onPress() {
    this.setState({n: this.state.n + 1});
  }

  render() {
    return <Button onPress={() => this.onPress()} />;
  }
}

Bind

The same function is reused on every render this is the ES6 best practice.

class AwesomeProject extends Component {
  constructor() {
    super();

    this.state = {n: 0};
    this.onPress = this.onPress.bind(this);
  }

  onPress() {
    this.setState({n: this.state.n + 1});
  }

  render() {
    return <Button onPress={this.onPress} />;
  }
}

Class properties

We remove the need for a constructor and avoid manually binding the handler. I personally think this is the cleanest way of doing this.

class AwesomeProject extends Component {
  state = {n: 0};

  onPress = () => {
    this.setState({n: this.state.n + 1});
  };

  render() {
    return <Button onPress={this.onPress} />;
  }
}