Fragments
As we saw in a previous lesson, we can only render one top level JSX element. If you try to render multiple sibling JSX elements without a parent element, you get this error: Adjacent JSX elements must be wrapped in an enclosing tag.
To overcome this, React allows you to render what are called Fragments. Fragments allow you to return a list of elements without adding an extra parent element to the DOM. We have provided an example that demonstrates the need for an element to only return a list of content elements, inside of a Content
component. We already have a Container
element that is its own React element, so it would be wasteful to need to wrap Content
in another <div>
.
We utilize the empty tag <>
to wrap our elements, the shorthand declaration for a fragment. Note that if you need to pass a key
to the fragment, you will need to use the longer syntax: <React.Fragment>
. A use-case for this is if you are rendering a list of fragments, you will need to pass a key
prop, so that would require using <React.Fragment key="123">
. This is a rare case that you may never encounter- If you were rendering a list of fragments, you would be better off abstracting the fragment into its own component as we've done here.
import React from "react"; import styled from "styled-components"; const Container = styled.div` padding: 10px; box-shadow: 0px 0px 5px silver; `; function Content() { return ( // A fragment is used to avoid rendering an extra container element <> <h1> 🏴☠️ Captain's Tasks </h1> <p> Manage the daily jobs at sea </p> </> ); } export default function App() { return ( <Container> <Content /> </Container> ); }