1

I have a link to return home and within that there is a button to remove an item from an array. To prevent the link to redirect to the home screen and to just remove the item from the array I am need to use ev.preventDefault().

Is it possible to pass an ev to a react method without using an arrow function in the render method? From my research and specifically the answer here it appears that the following is the only way to do so.

I am concerned that the arrow function causes a re-render every time, since new function is created on each render.

removeItem(label, e) {
    e.preventDefault();
    this.props.removeItem(label.id);
}


render () {
    const { label } = this.props;
    return (
      <Link to'/'>
        <span>Go Home</span>
        <span onClick={(e) => this.removeItem(label, e) }> Click me <span>
      </Link>
    );
}
Community
  • 1
  • 1
peter flanagan
  • 9,195
  • 26
  • 73
  • 127

2 Answers2

4

You could just remove the label parameter and get label from this.props directly. Refactor your app like this:

removeItem(ev) {
    ev.preventDefault();
    this.props.removeItem(this.props.label.id);
}


render () {
    const { label } = this.props;
    return (
      <Link to'/'>
        <span>Go Home</span>
        <span onClick={this.removeItem}> Click me <span>
      </Link>
    );
}

This way, React will automatically pass the click event to your removeItem method.

Although, it should be said, that creating a new function on every render, probably isn't all that expensive.

Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
0

In the light of avoiding to re-create the function you could extract the parameters into the class props. Here are some examples

For example this will create a new function all the time.

var List = React.createClass({
  render() {
    return (
      <ul>
        {this.props.items.map(item =>
          <li key={item.id} onClick={this.props.onItemClick.bind(null, item.id)}>
            ...
          </li>
        )}
      </ul>
    );
  }
});

Now it will not re-create the functions on re-rendering.

var List = React.createClass({
  render() {
    return (
      <ul>
        {this.props.items.map(item =>
          <ListItem key={item.id} item={item} onItemClick={this.props.onItemClick} />
        )}
      </ul>
    );
  }
});

var ListItem = React.createClass({
  render() {
    return (
      <li onClick={this._onClick}>
        ...
      </li>
    );
  },
  _onClick() {
    this.props.onItemClick(this.props.item.id);
  }
});

Here is some SO explanation React js onClick can't pass value to method

Community
  • 1
  • 1
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107