I’m trying to do the following… Note that "output.push();" does not have an ending div tag. but is separately ended at the bottom "output.push();"
What I’ve done there does not work. I’m trying to encapsulate everything inside the For loop in a single div and className. How can I achieve this please?
function IterateSectionFields({ props, tabIndex, sectionIndex }) {
return (
<div>
{(() => {
const output = [];
output.push(<div className="field-group">);
for (var i = 0; i < sectionFieldList.length; i++) {
//Do some more stuff
output.push(<div> A few things </div>);
}
output.push(</div>);
return output;
})()}
</div>
);
}
2
Answers
thanks all. That means I can't use push for my scenario. The logic just doesn't work. I eventually resolved it by saving multiple variables and then concatenating them.
Something like this:
You can’t push
<div>
without closing it to an array. All JSX elements need to be full, closed tags. React created html elements, not code. You can’t even convert your JSX to Javascript without having properly matched tags.Note that
output.push <div>{hello}</div>
actually gets compiled into:Note the Javascript does not have the concept of "opening" or "closing" tags. Just elements.
To fix your code just add only complete elements to the
output
array, and just move the div to the surrounding HTML.