7

Why do I have to put data-* in every html child attribute so i won't get undefined by clicking on parent? I.e

<li data-item="item-1">
  <img src="../img" alt="img" />
  <p>Some text</p>
</li>

By this example i will get item-1 whenever i click near the borders of <li> but whenever i click either img or text/paragraph i get undefined. But when I set data-item on <li> childs i get normal data value. What?

PS. The way i get data-* is for example

handleClick(event){
  let data = event.target.dataset['item']
}
...
<li data-item="item-1" onClick={this.handleClick.bind(this)}>...</li>

What am I doing wrong, that I have to put into every <li> child data-* so I won't get undefined on whole <li> block on<Event>?

1 Answer 1

13

FYI, the problem has nothing to do with React. It's how DOM events in browsers work. Have a look at this quirksmode.org article to learn more about how event propagation works.

event.target will always refer to the element the event was triggered on. So if you click on the <p> element, event.target will refer to that element. Since <p> doesn't have a data-* attribute you get undefined.

To always get the element where the handler is bound to (i.e. the <li> element in your example), use event.currentTarget instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, indeed that solves the problem. Thanks for TL;DR and the article about event.targets

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.