R
R
Radoncheg2019-07-31 19:35:28
React
Radoncheg, 2019-07-31 19:35:28

How to avoid bind in JSX?

I am newbie. I wonder how to avoid bind in the react code and do it differently so that the function is not re-created each time?
For example, here is the code in the render:

<i className="fa fa-trash-o icons" onClick={this.removeNote.bind(this, note.id)}/>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-31
@Radoncheg

In your case, you can leave it as is. Can be changed like this:

class Example extends React.Component {
  removeNote = () => {
  };

  render() {
    const { note } = this.props;

    return (
      <i className="fa fa-trash-o icons" onClick={() => this.removeNote(note.id)}/>
    );
  }
}

You can go further:
class Example extends React.Component {
  removeNote = e => {
    const { id } = e.currentTarget.dataset;
  };

  render() {
    const { note } = this.props;

    return (
      <i className="fa fa-trash-o icons" data-id={note.id} onClick={this.removeNote} />
    );
  }
}

In general, if you need to pass additional data to the handler, you can use both bind and anonymous arrow functions, and you should do optimization when it is necessary.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question