Moshe
Moshe

Reputation: 5139

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

Upvotes: 3

Views: 1277

Answers (2)

klaasman
klaasman

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

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

Upvotes: 3

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

Related Questions