6

const onClick = (e) => {
  console.log(e.target);
}
const App = () => (
  <button
    name={'YES'}
    className="btn waves-effect waves-light left blue darken-4"
    onClick={onClick}
  >
    Yes
    <i className='material-icons left'>done</i>
  </button>
);

ReactDOM.render(<App />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app">

I need e.target to be <button> in all possible cases, but when I click on <i>(or any other element as it seems), the target is <i> respectively. Its probably not error, but i don't know what to do about it.

Piliponful
  • 142
  • 3
  • 10
  • This is known as event bubbling. http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing. In order to help you here we would need to know why you want the target to be button, not how to do it. – azium Mar 06 '17 at 19:57

1 Answers1

17

Use event.currentTarget, which will always be the element on which the handler was added. event.target will always be the element on which the event occurred.

<button
  name={answerTypes.YES}
  className="btn waves-effect waves-light left blue darken-4"
  onClick={this.onClick}
>
  Yes
  <i className='material-icons left'>done</i>
</button>

onClick(e) {
  console.log(e.currentTarget);
}
Ross Allen
  • 43,772
  • 14
  • 97
  • 95
  • 1
    That's strange. Why do we need both? It is so confusing. How do I know which is the `event.target`? I click on the same `div` but only `currentTarget` will work. `event.target` only sometimes works. – newguy Apr 27 '18 at 03:17
  • 1
    @newguy We need both because events in the DOM [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Bubbling_and_capturing_explained); `event.target` changes as the event bubbles up the DOM hierarchy. Check out the docs and ask another question on SO if you have a specific issue. – Ross Allen Jun 08 '20 at 13:24