-1

I want to declare data- attributes on my react Elements and i want to know which type of referencing is better?

Doing ref and useRefs ?

`` declaring Data-{dataname} ``` ?

is any other way ?

when i used data- way i got undefiend data in mapping ...

    const stuffsList = stuffs.map((stuff) => (
      <div
        id="stuffsList"
        key={stuff.id}
accessKey={stuff.label}
        data-energies={stuff.nutrients.energy}
      >
        {stuff.label} {stuff.cat.child}
      </div>
    ));

I mapped this code , and it just render first data, not the data deponds on KEY

This is vhat i tried :

    const stuffsDiv = document.getElementById("stuffsList");

    console.log(stuffsDiv.dataset);

    const newStuff = {
      label: e.target.accessKey,
      energy: stuffsDiv.dataset.energy,
    };
tafhim
  • 123
  • 9

1 Answers1

0

You could test codes below :

// Example class component
class Thingy extends React.Component {
   constructor(props) {
   super(props)
   this.state = {
      objList:[
         {
            id:"1",
            label:"A",
            type:"APlus"
         },
         {
            id:"2",
            label:"B",
            type:"BPlus"
         }
      ]
    }
    this.refArray =[];
  }
  
 
   
  createDomElements=()=>{
     let keyCount = 0
     let output = this.state.objList.map((obj)=>(
        
           <div className="demoDiv" key={obj.id} id={obj.id} domLabel={obj.lable} data-type={obj.type} ref={domRef=>(this.refArray[obj.id]=domRef)} >{obj.id}</div>
        )
     )
     return output
  }
  
  getDataset=()=>{
     //let stuffsDiv = document.getElementById("1");
     let stuffsDiv = this.refArray[2]
     stuffsDiv.dataset.setAnotherProps = "This is another prop"
     console.log(stuffsDiv.dataset.setAnotherProps)
     console.log(stuffsDiv.dataset.type)
     console.log(stuffsDiv.dataset)
  }
  
  render() {
  
   
    return (
      <div>
         {this.createDomElements()}
         <button type="button" onClick={this.getDataset}>get data-set</button>
      </div>
    )
  }
}

// Render it
ReactDOM.render(
  <Thingy title="I'm the thingy" />,
  document.getElementById("react")
);
.demoDiv {
  width:100px;
  height:20px;
  background-color:red;
  margin:10px

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Update

Your questions:

which way to delcare dataset attribute in Dom element is better in React ?

It's no difference between this way: domElement.dataset.custome and this way: domElement.getAttribute('data-custome')

How to access custom attributes from event object in React?

which type of referencing is better?

I suggest React.createref() is better way to ref DOM element.

reactjs this.refs vs document.getElementById

In your case, because you want to use ref in mapping, you could declare ref as an array at first, like this.refArray=[] (You could see my code)

Problem that you got undefined when use dataset data-

The problem is in your mapping code, all elements got the same ID "stuffsList"

 const stuffsList = stuffs.map((stuff) => (
      <div
        // id="stuffsList"             //This line is wrong
        id={stuff.id}
        key={stuff.id}
        accessKey={stuff.label}
        data-energies={stuff.nutrients.energy}
      >
        {stuff.label} {stuff.cat.child}
      </div>
 ));

it just render first data,not the data deponds on KEY

I am not sure what you mean actually, because in my code, two mapping div elements render well. I suggest what you want to say is: When you log console.log(stuffsDiv.dataset), always log the data- attributes of first element. The reason is that in your code, every element you map has the same ID, and when multiple ID are, getElementById alway returns the first element.

Can multiple different HTML elements have the same ID if they're different elements?

Kuo-hsuan Hsu
  • 677
  • 1
  • 6
  • 12