0

How to correct set data about item in callback when i iterate list? I found this solution:

handleKeyPress = (item) => (e) => {...}
...
onClick={handleKeyPress(item)}

Is it not bast way maybe?

platypussss
  • 159
  • 8
  • But, obviously when component re renders happens create a new closure function. Is it not best way maybe? I guess better way to put item's id in a data attribute. And find item later, isn't it? – platypussss Sep 23 '17 at 04:33
  • First of all the above approach shouldn't work since handelKeyPress is being called on every render, secondly you are right every rerender creates a new function, the solution is to create a wrapper around the component and then pass the desired values, See this https://stackoverflow.com/questions/45053622/how-to-avoid-binding-inside-render-method – Shubham Khatri Sep 23 '17 at 05:08
  • Thanks, for answer! Ok, handelKeyPress it's not good example. What about onClick function? Handler'll be look like: handler = (e) => { const item = list[event.target.dataset.id]; ... } – platypussss Sep 23 '17 at 05:24
  • 1
    there are two approched to avoid, `onClick={()=>{this.handleKeyPress(item)}}`, one that I mentioned in the above answer, to create a wrapper component and pass back the props and second to memoize the function like `onClick={this.handleKeyPressLister(item)}` and using it `handleKeyPressListener(item) { return this.handleKeyPress.bind(this, item); }` where handleKeyPressListener is memoized function – Shubham Khatri Sep 23 '17 at 05:27

0 Answers0