Let's say I create a data-custom attribute in JSX element to save some meta-data about that element.
Like:
return (
<button data-customData="red" onClick={(ev) => { console.log(ev.target.customData)}}>Teste</button>
)
If I try to acess the data-custom attribute like you see in the code I will get undefined
.
But If I try something like ev.target.style
or ev.target.id
I will not get undefined.
What is the difference and how can we acess this value ?
CodePudding user response:
you're not calling the right value, you are calling a property called customData
but the attribute name is data-customData
, and in order to get the value you need to change how you call the attribute using the getAttribute
function that the element (ev.target) provides
return (
<button
data-customData="red"
onClick={(ev) => {
const element = ev.target;
console.log(element.getAttribute("data-customData"));
}}
>
Click Me
</button>
)
The thing you're trying to is not a very common pattern and if you want to get a value from the user you should use the right control (input, radio, select) instead of using a data attribute.