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.
And render
doesn’t support overloading like createElement
.
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.
GPT4 take:
Render two elements side-by-side with React Fragments
In this lesson, we will explore how to render sibling elements without adding extra nodes to the DOM by using React Fragments.
Reset the Example:
- Clear previous examples and set up a simple “Hello React” element.
Rendering Siblings:
-
Break the
div
into two separatespan
elements. -
Discuss the problem with rendering two elements without an enclosing tag.
Using a Wrapper div
:
-
Wrap both elements in a
div
to render them together. -
Point out the downside: an extra DOM node that might be unnecessary.
Introducing React Fragments:
- Replace the
div
with aReact.Fragment
to avoid adding extra nodes.
The Short Syntax for Fragments:
- Use the empty tag syntax
<>...</>
as a shorthand forReact.Fragment
.
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.