Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: [
            ...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") ?

like image 889
edmamerto Avatar asked Dec 30 '18 19:12

edmamerto


People also ask

How do you bind event handlers in React?

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.

Why would you need to bind event handlers to this?

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.


1 Answers

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)

like image 115
Chris G Avatar answered Sep 28 '22 16:09

Chris G