use React.createElement inside nested loop

Issue

I have a nested loop and would like to append react elements to a root element in order to be passed to a different component.

Something like this:

let ul = React.createElement('ul', null, []);

properties.forEach((property) => {
   errors[property].error.map((e: any) => {
       React.createElement('li', null, e);
   });
});

question is: how do I append the ‘li’ to the parent ‘ul’ element?

Solution

React discourages you from interacting with rendered content. Instead it wants you to render the right way in the first place. So I don’t believe React provides a way to append children to an already rendered element.

But that third argument is the children of an element. So you can iterate over the properties first, and then pass the result to the ul rendering call.

Something like this:

const lis: React.ReactNode[] = []

properties.forEach((property) => {
   errors[property].error.forEach((e: any) => {
       lis.push(React.createElement('li', null, e));
   });
});

const ul = React.createElement('ul', null, lis);

Answered By – Alex Wayne

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published