Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice for retrieving the data-attribute value in React

Tags:

reactjs

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

like image 493
Moe-Joe Avatar asked Aug 10 '17 01:08

Moe-Joe


People also ask

How do you get data attribute value in React?

Use the target. dataset property to access data attributes from the event object in React. The dataset property provides read and write access to the custom data attributes of the element. The property returns a Map of strings which can be converted to an object.

How do you pass values inside attributes in React?

Pass Dynamic Values to an Attribute The example below demonstrates this. Create one state variable with a default value. Now create the <input> element along with the required attributes. In the above example, the game-changer props are onChange() , used to update the existing value with the updated value.

What is the best way to handle a large data in React?

react-virtualized was specifically designed for rendering large lists and tabular data. It uses a technique similar to infinite scroll called windowing that renders only the visible parts of a list to the screen.

What are the two ways of getting data handled in React?

There are basically two ways in which the data gets handled in React. It gets handled through state and props. In another way, it can be said that two types of Model in React are there to manage the data for the components. Both state and props are plain JavaScript objects.


1 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')
like image 146
TechnicalKeera Avatar answered Sep 28 '22 19:09

TechnicalKeera