ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Sunday, November 13, 2022

[FIXED] How to get value of data custom-attribute in JSX / React

 November 13, 2022     jsx, reactjs   

Issue

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 ?


Solution

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.



Answered By - jean182
Answer Checked By - - Pedro (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix