React - how to use fragments
In this article, we would like to show you how to use fragments in React.
Quick solution:
xxxxxxxxxx
import React from 'react'; // do not forget to import this package!!!
const MyComponent = () => {
return (
<>
<div>Element 1</div>
<div>Element 2</div>
{/* Insert more elements here ... */}
</>
);
};
To render multiple elements in React, we need to wrap them with a <div>
because components can only return a single element. However, there are situations when we don't want to create an additional element in the DOM. That's when we can use React fragments.
Below example presents a situation when we want to externally implement columns for our table. In order for TableColumns
to render multiple elements, we have to render our cells inside one element. Wrapping them with a <div>
will lead to errors, so we use <React.Fragment>
instead.
Note:
We can also use React fragments short syntax
<> </>
(an empty tag) to wrap the elements.
Runnable example:
xxxxxxxxxx
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const TableColumns = () => {
return (
<React.Fragment>
<td style={{ border: '1px solid black' }}>cell 1</td>
<td style={{ border: '1px solid black' }}>cell 2</td>
<td style={{ border: '1px solid black' }}>cell 3</td>
</React.Fragment>
);
};
const Table = () => {
return (
<div>
<table style={{ border: '1px solid black' }}>
<tbody>
<tr>
<TableColumns />
</tr>
</tbody>
</table>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<Table />, root );
short syntax example:
xxxxxxxxxx
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const TableColumns = () => {
return (
<>
<td style={{ border: '1px solid black' }}>cell 1</td>
<td style={{ border: '1px solid black' }}>cell 2</td>
<td style={{ border: '1px solid black' }}>cell 3</td>
</>
);
};
const Table = () => {
return (
<div>
<table style={{ border: '1px solid black' }}>
<tbody>
<tr>
<TableColumns />
</tr>
</tbody>
</table>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<Table />, root );