Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React, why do I have to bind an onClick function rather then calling it?

In this tutorial he uses an onClick function with bind.

<Card onClick={that.deletePerson.bind(null, person)} name={person.name}></Card>

When I remove the bind like this

<Card onClick={that.deletePerson(person)} name={person.name}></Card>

I get an error

Uncaught Error: Invariant Violation: setState(...): Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.

I know what bind does, but why is it needed here? Is the onClick not calling the function directly?

(code is in this JSbin: https://jsbin.com/gutiwu/1/edit)

like image 726
ilyo Avatar asked Apr 07 '15 15:04

ilyo


1 Answers

He's using the bind so that the deletePerson method gets the correct person argument.

Because the Card component doesn't get a full Person object, this allows him to identify which person's card was actually clicked.

In your example, where you removed the bind onClick={that.deletePerson(person)} is actually evaluating the function that.deletePerson(person) and setting that as onClick. The deletePerson method changes the Component's state, which is what the error message is saying. (You can't change state during a render).

A better solution might be to pass the id into Card, and pass it back up to the app component on a delete click.

var Card = React.createClass({
  handleClick: function() {
    this.props.onClick(this.props.id)
  }
  render: function () {
      return (
          <div>
              <h2>{this.props.name}</h2>
              <img src={this.props.avatar} alt=""/>
              <div></div>
              <button onClick={this.handleClick}>Delete Me</button>
          </div>
      )
  }
})

var App = React.createClass({

  deletePerson: function (id) {
    //Delete person using id
  },

  render: function () {
    var that = this;
    return (
        <div>
            {this.state.people.map(function (person) {
                return (
                    <Card onClick={that.deletePerson} name={person.name} avatar={person.avatar} id={person.id}></Card>
                )
            }, this)}
          </div>
      )
  }
})
like image 198
Crob Avatar answered Oct 17 '22 04:10

Crob