1

I have a thing in React like this

<li id="my-id" onClick={this.handleClick}>
  <span>Something here</span>
  <i>Some italic text here</i>
</li>

Where I need to access the id of my LI.

handleClick(ev) {
  console.log(ev.target);
}

The thing is that when I click on the italic text, it console me the i element, not the li as it should.

Can someone explain me why, and how can I make onClick to return my li element?

Hiero
  • 2,182
  • 7
  • 28
  • 47
  • "Why" is because this is how React works, e.g., http://stackoverflow.com/a/32562118/438992. This is the same as how, say, jQuery works: the target is what's clicked on, `currentTarget` is where the handler was attached. – Dave Newton Apr 13 '16 at 13:26

1 Answers1

10

You need use .currentTarget instead of .target

handleClick(ev) {
  console.log(ev.currentTarget);
}

.currentTarget refers to the element where event handler has been attached to as opposed to .target which identifies the element on which the event occurred.

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144