Class properties with React
Dale L. Jefferson
Posted on May 30, 2019
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} />;
}
}
đź’– đź’Ş đź™… đźš©
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
programming How to visualize bar chart with react-chart-2, showing label on the bar
November 28, 2024
webdev 🚀 Introducing Folio-Motion: A Stunning Developer Portfolio Template! 🎨
November 28, 2024