-1

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 ?

5
  • 1
    dataset.color Commented Nov 13, 2022 at 22:15
  • ev.target.value; Referencing stackoverflow.com/questions/36683770/… Commented Nov 13, 2022 at 22:16
  • 1
    ev.target.dataset.customData Commented Nov 13, 2022 at 22:24
  • Does this answer your question? How can I get the data-id attribute? Commented Nov 13, 2022 at 22:27
  • ev.target.dataset.customData and ev.target.getAttribute('data-customData') work ! Commented Nov 13, 2022 at 22:27

1 Answer 1

3

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.

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

Comments

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.