2

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);
  }
}
1
  • write it like this: onClick={() => this.onClick(item.id)} or onClick={this.onClick.bind(this, item.id)} Commented May 28, 2019 at 6:14

1 Answer 1

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={()=>{ ... }}

Sign up to request clarification or add additional context in comments.

8 Comments

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 you mean if items has no item, you don't want to execute map()?
yes and the size of the items are dynamic.
@Gauranga it's easy, {(this.props.items || []).map(item => <button key={item.id} item={item} onClick={this.onClick} /> maybe I don't understand what you exactly want.
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
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.