Is it possible to use arrow functions in classes with ES6?
In order to do that, you'll need to add the transform-class-properties
babel plugin, which allows you to have auto-bound class methods like you are attempting.
Unlike what others have just suggested, there IS value in doing this. Namely, your class function automatically has the class this
bound to it, without having to manually bind it in your constructor.
Without the transform-class-properties
plugin, you could do:
export default class SearchForm extends Component {
constructor(props) {
super(props)
this.doSomething = this.doSomething.bind(this)
}
doSomething () {
console.log(this) // <-- 'this' is the class instance
}
}
With the plugin:
export default class SearchForm extends Component {
doSomething = () => {
console.log(this) // <-- 'this' is the class instance, no binding necessary
}
}
Heres and article that explains it (among other thing) fairly well and consisely: https://medium.com/@joshblack/writing-a-react-component-in-es2015-a0b27e1ed50a