Languages
[Edit]
EN

React - how to use fragments

0 points
Created by:
sienko
353

In this article, we would like to show you how to use fragments in React.

Quick solution:

const TableColumns = () => {
  return (
    <>
      <td style={{ border: '1px solid black' }}>cell 1</td>
      <td style={{ border: '1px solid black' }}>cell 2</td>
    </>
  );
};

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:

// ONLINE-RUNNER:browser;

// 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:

// ONLINE-RUNNER:browser;

// 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 );

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join