Render two elements side-by-side with React Fragments
Reset the to clear up all the previous examples and just get back to “Hello React”.
What happens if we break
<div>Hello React</div> into two elements?
How do I
render both of them? They can’t both be the first argument.
render doesn’t support overloading like
We could create another
div and wrap the two together.
But this isn’t always ideal because it inserts an extra DOM node.
Well, React gives us a solution for this. We can use a React Fragment, which is a special React element that doesn’t render to the DOM.
This is so common that JSX has a special, and memorable syntax for it: empty tags.
This is very useful for elements like tables and definition lists that have a very specific dom structure.
In this lesson, we will explore how to render sibling elements without adding extra nodes to the DOM by using React Fragments.
- Clear previous examples and set up a simple “Hello React” element.
divinto two separate
Discuss the problem with rendering two elements without an enclosing tag.
Wrap both elements in a
divto render them together.
Point out the downside: an extra DOM node that might be unnecessary.
- Replace the
React.Fragmentto avoid adding extra nodes.
- Use the empty tag syntax
<>...</>as a shorthand for
React Fragments are particularly useful for components that require a specific DOM structure, like tables or definition lists, where extra divs can break the desired layout.
By using React Fragments, we keep our DOM clean and semantic, exactly how we want it.