Reactjs function binding on event handler


I'm trying to understand why we have to bind an object null to the function

add(text) {
    this.setState(prevState=> ({
        notes: [
                id: this.nextId(),
                note: text

render() {
    return (
        <div className="board">
            <button onClick={this.add.bind(null, "New Note")}
                id="add">Add note</button>

Why can't we just do this.add("New Note") ?

Chris G

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)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at


Login to comment