Can’t bind methods in the constructor
Hello guys, I’d like to know why I can’t bind submitMessage() and handleChange() in the constructor for this exercice ?
Also, it is a best practice to bind these methods in the render method ?
This is what I’d like to do :
class DisplayMessages extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
messages: []
}
this.handleChange = this.handleChange.bind(this)
this.submitMessage = this.submitMessage.bind(this)
}
// add handleChange() and submitMessage() methods here
handleChange(event){
this.setState({
input: event.target.value
})
}
submitMessage(){
this.setState({
input: '',
messages: [...this.state.messages, this.state.input]
})
}
render() {
return (
<div>
<h2>Type in a new Message:</h2>
{ /* render an input, button, and ul here */ }
<input onChange={this.handleChange} value={this.state.input}/>
<button onClick={this.submitMessage}>Submit</button>
<ul>
{this.state.messages.map((x, i)=>{
return <li key={i}>{x}</li>
})}
</ul>
{ /* change code above this line */ }
</div>
);
}
};
Challenge: React and Redux - Manage State Locally First
Hello guys, I’d like to know why I can’t bind submitMessage() and handleChange() in the constructor for this exercice ?
Why do you think you can’t?
Also, it is a best practice to bind these methods in the render method ?
If you need to bind this to a method in a component, class, then yes.
Another option is to use an arrow function as a method:
class DisplayMessages extends React.Component {
myMethod = () => {
this.setState( /* ... */ ) // A OK
}
render() {
return (
//...
)
}
};
There is no need to bind this because an arrow function does not create its own and will inherit the one from the class.
In the “real world”, React developers don’t use class components much anymore, preferring functional components and hooks. (But you still need to learn class components.)