简体   繁体   中英

Set ID for each div from Array

Hey guys here is an example of what i am trying to do:

   const array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
    const divsArray = document.querySelectorAll(".myDiv");
    const changeDivId = (arr) => {
        arr.forEach((element, index) => {
            divsArray[index].id = element;
        });
    };

    changeDivId(array);
   return (
        <div className="myDiv">
...

Long story short i am trying to pass an ID from my array from above to each one of my div's. But it seems that i have an error of id of undefined. What am i doing wrong? Can someone give me a hand? The final result that i am expecting to see is:

<div className="myDiv" id="1" />
<div className="myDiv" id="2" />
<div className="myDiv" id="3" />
<div className="myDiv" id="4" />
<div className="myDiv" id="5" />
...

Looks like you're using React.

You shouldn't manually edit the DOM in JSX (which is the underlying markup syntax of React) because of how the virtual DOM works.

If you change an id using a querySelector , you will only be changing the DOM, but the virtual DOM remains unchanged.

Therefore, next time React re-renders, your DOM update will not be there.

This is why you should do it using JSX propper syntax:

const ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];

return (
  <>
    {ids.map(id => {
      return <div id={id} key={id}></div>
    })}
  </>
)

And just on a side note, you know you probably shouldn't use 1, 2, 3 as ids, right? They should be UNIQUE on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM