MENU
Fragment
Sometimes it is not possible to define a component on one single root element, in which case we should use a fragment.
The following two code snippets are identical, with the second one being the shorthand syntax (not supported in all environments).
RESETRUNFULL
RESETRUNFULL
class Columns extends React.Component {
render() {
return (
<React.Fragment>
<td>A</td>
<td>B</td>
<td>C</td>
</React.Fragment>
);
}}
class Columns extends React.Component {
render() {
return (
<>
<td>A</td>
<td>B</td>
<td>C</td>
</>
);
}}
RESETRUNFULL
Fragments declared with the explicit <React.Fragment> syntax may have keys. A use case for this is mapping a collection to an array of fragments — for example, to create a description list.
function Glossary(props) {
return (
<dl>
{props.items.map(item => ( // Without the `key`, React will fire a key warning
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
);}