React Component without parent element – React Fragments

Why react component without parent element or node is so important. For example if you want to import component with “<td>” elements for your table component. Actually you can’t do that without having a parent element to wrap those “<td>” elements. Like below.
class Columns extends React.Component {
  render() {
    return (
      <div>
        <td>Hello</td>
        <td>World</td>
      </div>
    );
  }
}

As you know you can’t insert such div elements. Because after “<tr>” element HTML DOM expect “<td>” or “<th>” element. Inserting “<tr>” will create new rows. So we need a way to import those “<td>” elements without creating a parent node.

React Fragments let you group a list of children without adding extra nodes to the DOM.

import React, {Fragment} from 'react';
class Columns extends React.Component {
  render() {
    return (
      <Fragment>
        <td>Hello</td>
        <td>World</td>
      </Fragment>
    );
  }
}

Below shows common example of React Fragments.

import React from 'react';
/** less **/
render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

Short Syntax for React Fragments

You can use <></> the same way you’d use any other element except that it doesn’t support keys or attributes.  Note that many tools don’t support it yet so you might want to explicitly write <React.Fragment> until the tooling catches up.

class Columns extends React.Component {
  render() {
    return (
      <>
        <td>Hello</td>
        <td>World</td>
      </>
    );
  }
}

key is the only attribute that can be passed to Fragment. In the future, we may add support for additional attributes, such as event handlers.

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.

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

Leave a Reply

avatar
  Subscribe  
Notify of