Best Practice for retrieving the data-attribute value in React

Viewed 12141

I have a question about React Syntax.
I was conceptualising a rebuild of my website in React and was writing code to access the data-attribute value.

The method I used to get the data-attribute value was:
e.target.getAttribute('data-menuItem');

and that seemed to work just fine. Upon further investigation I read about the alternative notation for the same method looks like:
e.target.attributes.getNamedItem('data-menuItem').value

I would just like to know if the second method I mentioned is best practice or if it really matters at all.

Your help is much appreciated. Thanks
Moe

2 Answers

Let suppose that you have <div data-pg="abc"></div> in your html then in react you can retrieve data attributes:

let val = e.target.dataset.pg

Now your val will have abc.

To retrieve value of data attribute, alternative way is:

let val = e.target.getAttribute('data-pg')
Related