I was wondering how I would go about getting the id (becuase it is unknown) of a button that is clicked. So when the button is clicked, I know what the id of that specific button is. There are lots of buttons on the page and I would like to know which button is pressed (they all have unique id's). Currently the buttons look like this:
<button key={uuidv4()} id={this.props.keyword} value={this.props.keyword} onClick={this.props.onClick} className="removeButton">Remove</button>
I know this has already been answered but i was working with react and faced similar issue, lost 2 hours trying to figure out why event.target.id was sometimes null or an empty string
this solved it for me:
class Button extends React.Component {
getButtonId = (e) => {
console.log(e.currentTarget.id);
}
render() {
return (
<button id="yourID" onClick={this.getButtonId}>Button</button>
);
}
}
Well if the elements are nested event.target
won't always work since it refers to the target that triggers the event in the first place. See this link for the usage of event.currentTarget
, which always refer to the element that the handler is bound to.
Another way to grab hold of the element and its attributes is to use React refs. This is more general when trying to get the DOM element in React.
The very convenient way (not only for buttons but for list of elements) to do this is using custom attribute data-someName
of DOM element and then reach it via event.currentTarget.dataset.someName
const openCard = (event) => {
console.log('event.currentTarget.dataset.id', event.currentTarget.dataset.id); // >> id
//do more actions with id
};
<Card onClick={openCard} data-id={item.id}>
<CardContent />
</Card>;
`
if the function to handle the event is in the same component it is best to use the event.target.id
, this will have its limitations when you try accessing a DOM element nested as a child component as event.target.id
. Use event.currentTarget.id
is nested,
This happens because event.currentTarget
can identify the element that caused the event deep down from the child as it burbles out, while event.target.id
will set the target as the child component and will not be able to identify the child component that has that element since it target does not change and hence faulty.
You can watch this youtube video to understand better. also read from their differences
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With