Class properties with React
Published in
1 min readDec 29, 2016
Using class properties you can simplify your handler functions. transform-class-properties is available via Babel and is included by default in React Native.
class AwesomeProject extends Component {
state = {n: 0}
handleOnPress = () => this.setState({n: this.state.n + 1})
}
With 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}
} handleOnPress() {
this.setState({n: this.state.n + 1})
} render() {
return <Button onPress={() => this.handleOnPress()} />
}
}
With 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.handleOnPress = this.handleOnPress.bind(this)
} handleOnPress() {
this.setState({n: this.state.n + 1})
} render() {
return <Button onPress={this.handleOnPress} />
}
}
With 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} handleOnPress = () => {
this.setState({n: this.state.n + 1})
} render() {
return <Button onPress={this.handleOnPress} />
}
}