0

I am trying to use onclick event like below

<button className="mini ui button" onClick={this.view(item['id'])}>
   <i className="user icon"></i>
   View
</button>

This is creating error like below

enter image description here

But below code is not creating error

<button className="mini ui button" onClick={this.view}>
     <i className="user icon"></i>
     View
</button>
abu abu
  • 6,599
  • 19
  • 74
  • 131
  • Possible duplicate of [React js onClick can't pass value to method](https://stackoverflow.com/questions/29810914/react-js-onclick-cant-pass-value-to-method) – Amanshu Kataria Apr 28 '18 at 07:29

2 Answers2

3

Change it to onClick={() => this.view(item['id'])}, otherwise the function gets executed immediately during rendering (instead of onClick), which causes repeated re-rendering if the function changes the state/props.

Roy Wang
  • 11,112
  • 2
  • 21
  • 42
  • Thanks @riwu. I faced this issue, the function gets executed immediately during rendering. – abu abu Apr 28 '18 at 05:13
  • Thanks @riwu. Could you please explain this code `onClick={() => this.view(item['id'])}` ? I am new in react.js – abu abu Apr 28 '18 at 05:15
  • `onClick` accepts a function. I'm using ES6 arrow function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Roy Wang Apr 28 '18 at 05:18
0

Yes you can use arrow function as previews answer or you can use bind

<button className="mini ui button" onClick={this.view.bind(this, item['id'])}>
   <i className="user icon"></i>
   View
</button> 

These two ways works.

Laura delgado
  • 362
  • 2
  • 8
  • 21