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)
}
Best way to handle this?

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.targetwhich identifies the element on which the event occurred.
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
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)
}
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