How to Wrap JSX Without Rendering Extra DOM Elements in React
React requires us to wrap all of our JSX inside a single parent element.
It often looks like this:
render() {
return (
<div>
<ChildA />
<ChildB />
</div>
)
}
The unfortunate part of all this is that we’re forced to add extra, unnecessary DOM elements to our components.
The great part of all this is that we have React.Fragment
, which allows us to render out a list of elements without creating that parent node.
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
</React.Fragment>
);
}
From v16.2.0
onward, we can use an alternative syntax to render fragments.
render() {
return (
<>
<ChildA />
<ChildB />
</>
);
}