2

I need to set state and run a function on a onClick event. How do I accomplish this in React?

I've atttempted to put these two things in their own function, but that give me this warning below.

Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

editLink(onEditLink, link) {
  this.setState({showContent: false});
  onEditLink(link);
}

render() {
  return (
    <a onClick={this.editLink(this.props.onEditLink, this.props.link)}>Edit</a>
  )
}
Community
  • 1
  • 1
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

2 Answers2

3

The problem is you are calling the function right away instead of assigning a new function which will be executed when the element is clicked:

editLink(onEditLink, link) {
  this.setState({showContent: false});
  onEditLink(link);
}

render() {
  return (
    <a onClick={() => this.editLink(this.props.onEditLink, this.props.link)}>Edit</a>
  )
}

What you want to do is pass a function, which when executed, will call your this.editLink function with those parameters.

Austin Greco
  • 32,997
  • 6
  • 55
  • 59
1

setState accepts a callback function as its second argument, I suggest you utilize that:

editLink(onEditLink, link) {
  this.setState({showContent: false}, () => {
     onEditLink(link);
  });
}

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

Rob M.
  • 35,491
  • 6
  • 51
  • 50