I'm trying to understand why we have to bind an object null to the function
add(text) {
this.setState(prevState=> ({
notes: [
...prevState.notes,
{
id: this.nextId(),
note: text
}
]
}))
}
render() {
return (
<div className="board">
{this.state.notes.map(this.eachNote)}
<button onClick={this.add.bind(null, "New Note")}
id="add">Add note</button>
</div>
)
}
Why can't we just do this.add("New Note")
?
To bind event handlers in React, the simplest, and the efficient way is to bind with arrow functions. Since this a new feature, it is not uncommon to see a lot of code using the binding in the constructor method. This is an equally efficient option to use.
When we bind the this of the event handler to the component instance in the constructor, we can pass it as a callback without worrying about it losing its context. Arrow functions are exempt from this behavior because they use lexical this binding which automatically binds them to the scope they are defined in.
onClick={this.add("New Note")}
would immediately run the add()
method, then set the result as onClick
. The result of add()
is undefined, because it doesn't return anything. So we'd essentially do onClick={undefined}
.
So to fix that, we can use an anonymous function: onClick={() => this.add("New Note")}
This time, the program properly calls this.add("New Note")
when the button is clicked.
Or we can just take advantage of the fact that bind()
allows us to state the this
context and the arguments we want to pass, and simply use onClick={this.add.bind(this, "New Note")}
(using this
as first argument binds the instance as context, just like the arrow function in the 2nd paragraph)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With