1

I am working on a react project. I was trying to pass item.id as the argument to the event handler. But I don't know how to send the value as the argument and how to access the value in the method. The program I was doing is shown below. Can someone help me to solve this issue?

class ItemList extends React.Component {
  constructor(props) {
    super(props);

    this.onClick = this.onClick.bind(this);
  }

  render() {
    return <div>
      {this.props.items.map(item =>
        <button key={item.id} item={item} onClick={this.onClick} />
      )}
    </div>;
  }

  onClick(itemId) {
    console.log('Clicked item:', itemId);
  }
}
Gauranga
  • 379
  • 1
  • 5
  • 11

1 Answers1

3
render() {
    return <div>
      {this.props.items.map(item =>
        <button key={item.id} item={item} onClick={()=>{this.onClick(item.id)}} />
      )}
    </div>;
  }

  onClick(itemId) {
    console.log('Clicked item:', itemId);
  }

you can use {()=>{...}}

NOTICE

If you write code like this onClick={this.onClick(item.id)}, It will be executed immediately when they are rendered.

so, you should keep wrapping them like this onClick={()=>{ ... }}

kyun
  • 9,710
  • 9
  • 31
  • 66
  • Thank you for replying, it is working now. I have one more doubt. I was trying to put a checkmark when we press the elements of the list is pressed. In order to do that I need to have a boolean array of the size that of items( list variable). But the list variable item is a dynamic one, so how to initialize the boolean variable with value 'false'. can anyone help me? – Gauranga May 28 '19 at 06:27
  • @Gauranga you mean if `items` has no item, you don't want to execute `map()`? – kyun May 28 '19 at 06:30
  • yes and the size of the items are dynamic. – Gauranga May 28 '19 at 06:33
  • @Gauranga it's easy, `{(this.props.items || []).map(item => ` maybe I don't understand what you exactly want. – kyun May 28 '19 at 06:35
  • The above code will work for both conditions. I think you didn't get my question. I want to create a dynamic boolean array based on the size of the items list variable so that I can use it in the onClick method – Gauranga May 28 '19 at 06:40
  • @Gauranga I don't understand what is `dynamic boolean array`. could you give me an example? – kyun May 28 '19 at 06:41
  • Dynamic boolean array means by a boolean array which has size dynamically calculated. Here the size of the boolean array should be equal to the length of the list – Gauranga May 28 '19 at 06:45
  • @Gauranga `[true, false, false, true, true]` like this? – kyun May 28 '19 at 06:52