Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button onClick target is changing

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? gif

like image 448
Moshe Avatar asked Apr 05 '26 21:04

Moshe


2 Answers

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 to event.target which identifies the element on which the event occurred.

https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

like image 164
klaasman Avatar answered Apr 08 '26 10:04

klaasman


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)
}
like image 20
Luis felipe De jesus Munoz Avatar answered Apr 08 '26 10:04

Luis felipe De jesus Munoz