React Fragments allow you to wrap or group multiple elements without adding an extra node to the DOM.
This can be useful when rendering multiple child elements/components in a single parent component.
function Parent () {
return (
<React.Fragment>
<Child1 />
<Child2 />
</React.Fragment>
);
}
React components can only render one element, and if you have multiple elements, the common practice is to wrap them in a single root element, usually a <div>
wrapper.
This workaround works for most cases, but sometimes adding an extra DOM element is not feasible.
Consider the following components and the resulting HTML.
React components:
function Column () {
return (
<div>
<td>Hello World!</td>
<td>Hello Educative!</td>
</div>
);
}
function Table () {
return (
<table>
<tr>
<Column />
</tr>
</table>
);
}
HTML:
<table>
<tr>
<div>
<td>Hello World!</td>
<td>Hello Educative!</td>
</div>
</tr>
</table>
If we wrap the <td>
elements in a <div>
, this will add a <div>
element in middle of <tr>
and <td>
and break the parent-child relationship.
In order to correctly render the HTML, <Column />
must return multiple <td>
elements without any extra element in between the <tr>
and <td>
tags.
React Fragments allow you to wrap multiple elements without adding an extra DOM element.
In our case, we replace the <div>
warpper with the Fragment element in the <Column />
component as follows:
function Column () {
return (
<React.Fragment>
<td>Hello World!</td>
<td>Hello Educative!</td>
</React.Fragment>
);
}
You can also use the short syntax for React Fragments, which are simply empty tags:
function Column () {
return (
<>
<td>Hello World!</td>
<td>Hello Educative!</td>
</>
);
}
import React from 'react'; import ReactDOM from 'react-dom'; import Table from './Table'; ReactDOM.render( <Table />, document.getElementById('root') );
Free Resources