Have you ever wanted the ability to render two components without having to wrap them in a parent using React? React v16.0.0 introduced fragments and to further enhance fragments, as of v16.2.0, you can now use React.Fragment
, or the shorthand syntax <></>
, to render components without a parent element. Take the following example where I want to display a button if the user is not logged in or a friendly message if they are logged in:
function Example(props) {
const loginButton = props.loggedIn ? 'Hello User!' : <button>Login!</button>
return (
<h1>Welcome</h1>
{loginButton}
);
}
Trying to render the above component will result in an error. Ultimately what you needed to do is wrap your H1 and loginButton in a div (or some other element). With React 16.2.0+ we can now wrap our components in a React Fragment and the rendered markup will only contain the markup for those children:
Let's take the code above and use the new React.Fragment component:
function Example(props) {
const loginButton = props.loggedIn ? 'Hello User!' : <button>Login!</button>
return (
<React.Fragment>
<h1>Welcome</h1>
<button>Login!</button>
</React.Fragment>
);
}
Now the HTML structure doesn't have any additional container elements:
<h1>Welcome</h1>
<button>Login!</button>
If you want to use the shorthand syntax just remove React.Fragment
from the code:
...
return (
<>
<h1>Welcome</h1>
<button>Login!</button>
</>
);
...
React documentation states that "...many tools don’t support it (<></>
) yet so you might want to explicitly write <React.Fragment>
until the tooling catches up."
For more details about fragments (including keyed fragments) check out the React Documentation on Fragments.
CodePen of the above example available here.
Happy Coding!