Reputation: 5139
I have a button with fa
icon inside it, and I attached an onClick event (React)
If I click on the button, the target of the handler is the button itself. If I click on the fa
icon that's inside the button, the target of the handler is the i
tag that is the fa
icon.
Example code:
<button onClick={changeViewType} value="boxes">
<i className="fa fa-th" style={{color: '#26d6ff'}}/>
</button>
<button onClick={changeViewType} value="table">
<i className="fa fa-list-ul"/>
</button>
Handler:
const changeViewType = selectedView => {
console.log(selectedView.target.value)
}
Upvotes: 3
Views: 1277
Reputation: 897
You should use event.currentTarget
instead of event.target
.
From the MDN docs:
It (
event.currentTarget
) always refers to the element to which the event handler has been attached, as opposed toevent.target
which identifies the element on which the event occurred.
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
Upvotes: 3
Reputation: 7923
Check if the target element is an I
. If so, take the parent, if not keep taking the original target.
const changeViewType = selectedView => {
target = selectedView.target.tagName == 'I'? selectedView.target.parentElement : selectedView.target;
console.log(target.value)
}
Upvotes: 1