-1

I want to pass a custom attribute to my option field named "data-id":

<option data-id={item.id}>{item.name}</option>

In my onChange function I know how to get the value, I'd do it like : console.log(e.target.value)

But how can you get a custom attribute like 'data-id'. Could you just do 'e.target.data-id' ? That didn't seem to work in my case. Is there a correct way of doing this (if it's even possible)

Kevin.a
  • 4,094
  • 8
  • 46
  • 82
  • `e.target["data-id"]`? – jonrsharpe Oct 14 '20 at 12:37
  • Does this answer your question? [How to access object property with invalid characters](https://stackoverflow.com/questions/21056075/how-to-access-object-property-with-invalid-characters) – jonrsharpe Oct 14 '20 at 12:38
  • Or the canonical https://stackoverflow.com/q/4968406/3001761. Or https://stackoverflow.com/q/33760520/3001761 specifically for HTML `data-` props. – jonrsharpe Oct 14 '20 at 12:39
  • May I ask you why you use data attributes in this case? Most of the time that shouldn't even be necessary. If the reason is that you want to identify which `id` was chosen then there are better ways to solve that in react. – trixn Oct 14 '20 at 12:46

2 Answers2

1

You can use the dataset property of the element. Have a look at this example:

const testDiv = document.querySelector('.my-div');

testDiv.addEventListener('click', e => {
  testDiv.innerText = e.target.dataset.id
})
.my-div {
  width: 50px;
  height: 50px;
  background: blue;
  color: white;
}
<div class="my-div" data-id="abc"></div>
Sagi Rika
  • 2,839
  • 1
  • 12
  • 32
1

You can access the values of data attributes through the dataset property:

const handleChange = e => {
    console.log(e.target.dataset.id)
}
trixn
  • 15,761
  • 2
  • 38
  • 55