Cuzto
Cuzto

Reputation: 135

React getting the ID of clicked button

I have 5 clickable links, each with unique ID. I am trying to get the ID of the link that was clicked. I have tried two methods but neither work as I would like.

Inside render I have:

this.state.data.map((dynamicData, key) =>
  <a href={"/#/template"} id={dynamicData.id} onClick={() => this.reply_click(this.id)}>{dynamicData.name}</a>
  <a href={"/#/addTeams"}><button type="button" class="btn-lisa">Edit</button></a>

Basic method that returns undefined. What am I doing wrong?:

reply_click(clicked_id) {
  console.log(clicked_id);
}

Upvotes: 1

Views: 22981

Answers (5)

Anton Harniakou
Anton Harniakou

Reputation: 880

Try this code. The code you have provided doesn't work because this is bound to the current React component, instead you could access id of the clicked element using e.target.id:

this.state.data.map((dynamicData, key) => {
  <a href="/#/template" id={dynamicData.id} onClick={(e) => this.reply_click(e.target.id)}>{dynamicData.name}</a>
  <a href="/#/addTeams"><button type="button" class="btn-lisa">Edit</button></a>
})

Unrelated, but still I want to note that you don't have to use <a href={"blah"} instead you can use <a href="blah" because the last one uses a string contant.

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 77030

The this inside the arrow function is the same as the this outside it. The onclick is already aware of the correct this, so use it like this:

onClick={this.reply_click(this.id)}

Upvotes: 0

Kevin Li
Kevin Li

Reputation: 2114

this.reply_click(this.id)

this is your component scope, which means every attribute you defined in your component can be accessed by this. Probably you did not define id in this component.

You probably wanna do

 this.reply_click(dynamicData.id)

instead.

Upvotes: 0

Giang Le
Giang Le

Reputation: 7054

you can do this

<a href={"/#/template"} id={dynamicData.id} onClick={() => this.reply_click(dynamicData.id)}>{dynamicData.name}</a>

or another way

<a href={"/#/template"} id={dynamicData.id} onClick={this.reply_click}>{dynamicData.name}</a>



reply_click(event) {
    console.log(event.target.getAttribute('id'))
}

Upvotes: 0

samanime
samanime

Reputation: 26615

Using an arrow function will maintain the context of this from the outside, which won't be the this you want. You could try to use a regular function (function () { }) instead, but I'm not sure if this will be what you want or not there either.

You can, however, definitely use e.target.id to get what you want:

onClick={e => this.reply_click(e.target.id)}

That said, you should really avoid creating functions inside of things as it can create significant performance issues. It's much better to just create a function and pass it in:

// somewhere above
const handleClick = e => this.reply_click(e.target.id);

// attribute
onClick={handleClick}

Upvotes: 5

Related Questions