Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data attributes with React.js

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

like image 755
nehel Avatar asked Jan 29 '17 22:01

nehel


People also ask

How do you get data attribute from event React?

Use the target. dataset property to access data attributes from the event object in React. The dataset property provides read and write access to the custom data attributes of the element.

Can I use data attributes in React?

To set a data attribute on an element in React, set the attribute directly on the element, e.g. <button data-test-id="my-btn"> or use the setAttribute() method, e.g. el. setAttribute('data-foo', 'bar') . You can access the element on the event object or using a ref .

How do I select attributes in React?

To select a default option in React, the selected attribute is used in the option element. In React, though, instead of using the selected attribute, the value prop is used on the root select element. So, you can set a default value by passing the value of the option in the value prop of the select input element.

How do I get tag value in React?

When the button element is clicked, the click event gets triggered, the value of the tagName property can be used to find out HTML element the source of the event and innerText property can be used to find out text written in that HTML element.


1 Answers

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.

like image 85
Felix Kling Avatar answered Oct 29 '22 22:10

Felix Kling