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
Technically: because there’s no syntactical element in the underlying JavaScript that could host three adjacent elements.
compiles down to
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
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.
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:
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.