Fragments
A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
Example:
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
Motivation
A common pattern is for a component to return a list of children. Take this example React snippet:
class Table extends React.Component {
render() {
return (
<table>
<tr>
<Columns />
</tr>
</table>
);
}
}
<Columns />
would need to return multiple <td>
elements in order for the rendered HTML to be valid. If a parent div was used inside the render()
of <Columns />
, then the resulting HTML will be invalid.
class Columns extends React.Component {
render() {
return (
<div>
<td>Hello</td>
<td>World</td>
</div>
);
}
}
results in a <Table />
output of:
<table>
<tr>
<div>
<td>Hello</td>
<td>World</td>
</div>
</tr>
</table>
Fragments solve this problem. Fragments also cut down on the number of wrapping divs that have no other use than fulfilling the JSX syntax requirement.
Short Syntax
There is a new, shorter syntax you can use for declaring fragments. It looks like empty tags:
class Columns extends React.Component {
render() {
return (
<>
<td>Hello</td>
<td>World</td>
</>
);
}
}
You can use <></>
the same way you’d use any other element except that it doesn’t support keys or attributes.
For more details see: React Docs