Skip to content
Advertisement

how to create a dynamic div on a React JS, and second is how to give that div a dynamic ID, this code below is JS code?

How to rewrite this code with React.js?

let tile = document.createElement("div");
      tile.id = r.toString() + "-" + c.toString();

Full code:

for (let r = 0; r < rows; r++) {
    for (let c = 0; c < columns; c++) {
      let tile = document.createElement("div");
      tile.id = r.toString() + "-" + c.toString();

      let num = board[r][c];
      updateTile(tile, num);
      document.getElementById("board").append(tile);
    }
  }
}

Advertisement

Answer

You can actually do this in your components render function, it would look something like this

return (
   <div id="board">
     {rows.map(row => {
        columns.map(column => (
          <div id={`${row}-${column}`} />
        ))
     })}
   </div>
)

Assume that div with id board is your board where you append created elements. Also I’m not sure what updateTile do, so if you would need some help with this, pls, share more details. And if you want just to render items, use code above

Advertisement