5

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") ?

3
  • is it working as expected after adding null? Commented Dec 30, 2018 at 19:10
  • Possible duplicate of this [link], you can get an explanation from this link (stackoverflow.com/questions/38334062/…) Commented Dec 30, 2018 at 19:11
  • Passing null shouldn't work . Are you sure it does? Commented Dec 30, 2018 at 19:39

1 Answer 1

8

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.