The DRY Way to Bind React Component Methods
// The Slow and Ugly Way
export default class Example extends React.Component {
constructor(props) {
super(props)
this.methodA = this.methodA.bind(this)
this.methodB = this.methodB.bind(this)
this.methodC = this.methodC.bind(this)
this.methodD = this.methodD.bind(this)
}
}
// The DRY and (Slightly) Better-Looking Way
export default class Example extends React.Component {
constructor(props) {
super(props)
const boundMethods = [
'methodA',
'methodB',
'methodC',
'methodD'
]
boundMethods.forEach(method => this[method] = this[method].bind(this))
}
}