skip to Main Content

So please bear with me.

if there is a div className as app already there, why do i need fragment for employee?
wouldn’t it be already under the single parent element <div className = "app>

return (
    <div className="app">
    { showEMployees ? 
    
      <>
      <Employee />
      <Employee />
      <Employee />
      </>
  
      :
      <p> YO YOU CANT ACCESS IT BRO</p>
      
    }
    </div>
  
  );

I tried deleting the div classname app but it says it still needs a parent element. and i deleted the fragment and it says the same thing.

2

Answers


  1. Technically: because there’s no syntactical element in the underlying JavaScript that could host three adjacent elements.

    /* @jsx r */
    <div>
      {showEMployees ? (
        <>
          <Employee />
          <Employee />
          <Employee />
        </>
      ) : (
        <p> YO YOU CANT ACCESS IT BRO</p>
      )}
    </div>
    

    compiles down to

    r(
      "div",
      null,
      showEMployees
        ? r(
            React.Fragment,
            null,
            r(Employee, null),
            r(Employee, null),
            r(Employee, null),
          )
        : r("p", null, " YO YOU CANT ACCESS IT BRO"),
    );
    

    see how a React.Fragment element was injected to hold the children? (When rendered into HTML elements by React, the fragment "disappears".)

    If you didn’t use a fragment, it’d compile down to

    (r(Employee, null), r(Employee, null), r(Employee, null))
    

    which would just be the comma operator and you’d end up with only one Employee element.

    You also shouldn’t use an array for a static number of elements.

    Login or Signup to reply.
  2. The error message you are receiving ("needs a parent element") is because JSX requires that there be a single parent element wrapping all the elements within a component. So, even if you removed the fragment (<> … </>), you should still have a single parent element that encloses all the elements inside the component.

    In your case, if you want to keep the "app" class as the parent element, you should avoid removing it. However, you can eliminate the fragment and use another element as a container.
    For example:

    return (
      <div className="app">
        {showEmployees ? (
          <div>
            <Employee />
            <Employee />
            <Employee />
          </div>
        ) : (
          <p>YO YOU CAN'T ACCESS IT BRO</p>
        )}
      </div>
    );
    

    This way, you have a single parent element (the with the "app" class) that contains the elements when showEmployees is true and the paragraph when showEmployees is false.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search