0

I want to know if there is a way to create and render multiple elements dynamically instead of having to manually write each one in React.

Coming from javascript there were options like the following:

let parent document.getElementById("parent");
let html = "";
for (let i = 0; i < 10; i++) {
html += "<div>Div + (i + 1) + "</div>";
}
parent.innerHTML

Or:

let parent = document.getElementById("parent");
for (let i=0; i < 10; i++) {
let div = document.createElement("div");
div.innerHTML = "Div + (i + 1);
parent.appendChild(div);
}

i tried for loops, making functions containing only the code for creating multiple divs, tried placing the function or the for loop in different places in my component or even outside of it. also tried looking up online but I can't seem to find an answer and I keep running into errors

  • 2
    Read more than the accepted answer. ie: this one has a good overview https://stackoverflow.com/a/29629588/13762301 . Also you shouldn't be using direct DOM queries except in very specific circumstances. – pilchard Jun 25 '23 at 23:22
  • @pilchard I'm more partial to [this answer](https://stackoverflow.com/a/46975826/283366) – Phil Jun 25 '23 at 23:23
  • Fair enough, spread vs Array.from (even I didn't scroll that far ;) ) – pilchard Jun 25 '23 at 23:25

0 Answers0