6

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); 
2
  • one ques, how you are generating the button dynamically, inside any loop ? Commented Apr 25, 2017 at 7:31
  • @MayankShukla Yes in map Commented Apr 25, 2017 at 7:33

4 Answers 4

14

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.

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

1 Comment

This works: onClick={() => that.handleRegionClick(item.id)} (use that instead of this in my case inside render)
2

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) } 

Comments

0

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); }); } 

Comments

-1

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

that.handleRegionClick.bind(that)

Then you should be able to access e.target

1 Comment

e.target gives me the form... not the button that was clicked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.