Why JSX Can Only Have One Parent Element
When you try to return multiple elements from a component, you will get an error message like this:
JSX is a syntactic sugar for
React.createElement, which is a function that takes three arguments: the tag, the props, and the children.
If you have a nested element, the children will be an array of
If you see the example, it actually makes sense
As we know, we can't return 2 elements from a function, so returning 2 parent elements in a component/map function is not possible.
There are two solutions to this problem:
By wrapping the elements in one parent element, we can solve the problem.
However, you are ending up with an extra element in the DOM tree. This might be your desired result, and mostly it is. Use this if you want to.
React.Fragment is a component that doesn't render anything in the DOM tree.
If you want to return multiple elements without adding an extra element in the DOM tree, use