[Question] question regarding best practice
Apologies for the none-standard git issue, but I wasn't quite sure where else to ask.
I'm working with another developer on a React project, using ES6. So I was just wondering, is there anything wrong or bad practice about using fat arrow functions hoisted, and parameters hoisted to a component class, which aren't set within the constructor? So for example...
class MyComponent extends React.Component {
constructor(props) {
super(props)
}
state = {
name: '',
}
setName = (e) => {
this.setState({ name: e.target.value })
}
}
My colleagues approach...
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
name: '',
}
this.setName = this.setName.bind(this)
}
setName(e) {
this.setState({ name: e.target.value })
}
}
The reason I use approach 1 is because it automatically scopes this within the function, so you don't need to write the additional line to bind a method within the constructor.
I figured ultimately this was down to preference as they both worth identically. But I've been told my way (first example) was bad practice.
Thanks in advance!
The possibility to use the property initializer syntax is mentioned in the official documentation : https://facebook.github.io/react/docs/handling-events.html I guess it is not a bad practice otherwise it would have been pointed out. There is just a warning about the fact that it is experimental syntax, so in the end it is up to you to decide to use the dedicated babel plugin and enable this feature or notre.
@EwanValentine On a side note, you don't need to pass in props in constructor and when calling the base class unless you don't need the props inside the constructor.
So,
constructor() {
super()
this.state = { name: '' };
}
should do fine as well.
Thanks folks! This is really helpful :)
For future reference, we try to use this issue tracker for bug reports and feature requests only. If you have a usage or support question, we recommend checking out one of the great community-driven platforms like Reactiflux, discuss.reactjs.org, or StackOverflow!