Giorgi Moniava
Giorgi Moniava

Reputation: 28654

Retrieve which button was clicked in React

I have several dynamically generated material UI buttons, and when user clicks any of them I would like to know which was clicked (let's say obtain the value of name attribute which I assigned below). How can this be solved? Basically I want to retrieve some attribute of the button which was clicked. Here is some code

    {
      that.state.items.map(function (item) {
        return (
          <div key={item.id}>
            <FlatButton
              label={item.regionName}
              name={item.id}
              primary={true}
              onClick={that.handleRegionClick}
            ></FlatButton>
          </div>
        );
      });
    }
    
    handleRegionClick(e);
    {
      console.log(e.target.name); // This prints undefined
      // If I could get here the _item.id_ which I assigned to _name_ I would be fine.
    }

PS. I also have this in constructor

 this.handleRegionClick = this.handleRegionClick.bind(this);

Upvotes: 6

Views: 17815

Answers (4)

Mayank Shukla
Mayank Shukla

Reputation: 104359

You can do one thing, instead of assigning the id to name, bind that id with onClick handler function. Whenever any of the button will be clicked, it will pass that id to handler function.

Like this:

let a = [{ id: 1 }, { id: 2 }, { id: 3 }];

a.map(item => {

   return <FlatButton
    label={item.regionName}
    primary={true}
    onClick={() => this.handleRegionClick(item.id)} />

})

handleRegionClick function:

handleRegionClick(id){
  console.log(id);
}

Note: binding of handleRegionClick is not required here because here, we are using arrow function with onClick and calling handleRegionClick normally.

Upvotes: 14

Peter G
Peter G

Reputation: 2821

Don't use onClick for this. Instead, when you generate the button, add an event listener. If you do that, then you can access the clicked element through e.toElement and access its name property with e.toElement.name (seems like your item.id is in the name property).

for (...) { // however many buttons you generate
    var x = generateButtonSomehow(); // make sure it returns the DOM element
    x.addEventListener('click', function(e) {
        console.log(e.toElement.name);
    });
}

Upvotes: 0

Thanh Nguyen
Thanh Nguyen

Reputation: 5342

Your question looks weird to me. You can simply do it.

<FlatButton label={item.regionName} name={item.id} primary={true} onClick={that.handleRegionClick.bind(this, item.id)}></FlatButton>

handleRegionClick(itemId){
  console.log(itemId)
}

Upvotes: 2

manelescuer
manelescuer

Reputation: 856

Maybe trying to bind that.handleRegionClick() to this?

that.handleRegionClick.bind(that)

Then you should be able to access e.target

Upvotes: -1

Related Questions