Its straightforward process;
Here is the origin render method I want it to be(I want my table outside of div):
but jsx compiler dont allow it for some reason?
but if i move the table inside of div element; everything looks ok.
so only diff is place of table. why jsx interfere this process ? why its necessary ?
In JSX
, we can return only one html
element from return
, can't return multiple elements, if you want to return multiple elements then wrap all the html code in a div
or by any other wrapper component.
Same thing is happening in your 1st case, you are returning 2 elements, one div
and one table
. when you are wrapping them in one div
everything is working properly.
Same rule you have to follow for conditional rendering
of components.
Example:
Correct:
{ 1==1 /* some condition */ ?
<div>
True
</div>
:
<div>
False
</div>
}
Wrong:
{ 1==1 /* some condition */ ?
<div>
True 1
</div>
<div>
True 2
</div>
:
<div>
False 1
</div>
<div>
False 2
</div>
}
Just a quick update. If you are using React v16.2.0 and above you also can use Fragments.
return (
<>
<div>
True 1
</div>
<div>
True 2
</div>
</>
);
I also replied to a similar question, more in depth here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With