Photo credit: Ambreen Hasan
Shorter syntax for state and bind/event handler functions in React.js classes
March 12, 2018 - 2 min read
If you’ve ever seen an older React.js component that contains state and/or an event handler function, i.e. handleClick, handleChange, etc. then you’ve probably seen the class written something like the example below:
import React, { Component } from 'react'
export default class DirtDevil extends Component {
constructor(props) {
super(props)
}
this.state = {
vacuumIsOn: false
}
this._handleClick = this._handleClick.bind(this)
_handleClick() {
this.setState({vacuumIsOn: !this.state.vacuumIsOn})
}
render() {
let {vacuumIsOn} = this.state
return (
<button onClick={this._handleClick}>
Power: {vacuumIsOn ? 'Off' : 'On'}
</button>
)
}
}
or maybe with the bind method like this:
import React, { Component } from 'react'
export default class DirtDevil extends Component {
constructor(props) {
super(props)
}
this.state = {
vacuumIsOn: false
}
_handleClick() {
this.setState({vacuumIsOn: !this.state.vacuumIsOn})
}
render() {
let {vacuumIsOn} = this.state
return (
<button onClick={this._handleClick.bind(this)}>
Power: {vacuumIsOn ? 'Off' : 'On'}
</button>
)
}
}
A new syntax
While there’s nothing wrong with the two approaches above, there’s a simpler syntax now for initiating state and binding event handler functions in React.js. All you need is to have the class properties proposal enabled for the experimental state syntax and the public class fields syntax enabled for the experimental bind syntax in your build tool configuration.
Note: Create React App has both of these syntaxes enabled by default. Also note that this syntax is experimental and could be changed.
import React, { Component } from 'react'
export default class DirtDevil extends Component {
state = {
vacuumIsOn: false
}
_handleClick = () => {
this.setState({vacuumIsOn: !this.state.vacuumIsOn})
}
render() {
let {vacuumIsOn} = this.state
return (
<button onClick={this._handleClick}>
Power: {vacuumIsOn ? 'Off' : 'On'}
</button>
)
}
}
Conclusion
The shorter syntax is a much easier and nicer looking way to initiate a React class with state and event handler functions. Enjoy and happy coding! SL