Class properties with React

daleljefferson

Dale L. Jefferson

Posted on May 30, 2019

Class properties with 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} />;
  }
}
đź’– đź’Ş đź™… đźš©
daleljefferson
Dale L. Jefferson

Posted on May 30, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related