skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    concatenatedOutput = (
        <>
            {concatenatedOutput}
            <div className="section-group">
                {heading}
                {content}
            </div>
        </>
    

  2. 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:

    array.push( /*#__PURE__*/_jsx("div", {
      children: hello
    }));
    

    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.

    function IterateSectionFields({ props, tabIndex, sectionIndex }) {    
          const output = [];
        
          for (var i = 0; i < sectionFieldList.length; i++) {
               //Do some more stuff 
               output.push(<div> A few things </div>);
          }
    
          return (
            <div>
               <div className="field-group">
                   { output }
              </div>
            </div>
        );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search