React Fragment Introduction and Detailed Usage

React Fragment Introduction and Detailed Usage

Preface

When adding elements to the DOM tree in batches, a good practice is to create a document.createDocumentFragment to first add the elements to the DOM tree in batches.
DocumentFragment, and then add DocumentFragment to the DOM tree, which reduces the number of DOM operations and does not create a new element.

Similar to DocumentFragment, React also has the concept of Fragment, which has similar uses. Before React 16, Fragment was created through the extension package react-addons-create-fragment, while in React 16, 'Fragment' is created directly through <React.Fragment></React.Fragment>.

Motivation for Fragments

A common pattern is for a component to return a list of child elements. Take this React code snippet as an example:

class Table extends React.Component {
  render() {
    return (
      <table>
        <tr>
          <Columns />
        </tr>
      </table>
    );
  }
}

<Columns /> needs to return multiple elements in order for the rendered HTML to be valid. If the parent div is used in the render() of <Columns />, the generated HTML will be invalid.

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

Get a < Table /> output:

<table>
  <tr>
    <div>
      <td>Hello</td>
      <td>World</td>
    </div>
  </tr>
</table>

Fragments came into being to solve this problem.

React Fragment Introduction and Use

React.Fragment component allows multiple elements to be returned from the render() method without creating additional DOM elements. A common pattern is for a component to return multiple elements. Fragments allow you to group sublists without adding extra nodes to the DOM.

To understand, when we define a component, the outermost div wrapped in the return often does not want to be rendered to the page, so we need to use our Fragment component. Just like Vue's <template ></ template >.

render() {
  return (
    <React.Fragment>
      Some text.
      <h2>A heading</h2>
    </React.Fragment>
  );
}

You can also use the shorthand syntax <></>.

render() {
  return (
    <>
      Some text.
      <h2>A heading</h2>
    </>
  );
}

In addition, starting from react 16, render supports returning arrays, and many people know this feature. This feature can already reduce unnecessary node nesting.

import React from 'react';

export default function () {
    return [
        <div>1</div>,
        <div>2</div>,
        <div>3</div>
    ];
}

Difference between <React.Fragment> and <>

The <></> syntax cannot accept keys or attributes, while <React.Fragment> can.

Fragments declared using the explicit <React.Fragment> syntax may have keys. One use case is mapping a collection to an array of Fragments - for example, creating a list of descriptions:

function Glossary(props) {
  return (
    <dl>
      {props.items.map(item => (
        // Without `key`, React will issue a key warning <React.Fragment key={item.id}>
          <dt>{item.term}</dt>
          <dd>{item.description}</dd>
        </React.Fragment>
      ))}
    </dl>
  );
}

key is the only attribute that can be passed to a Fragment. Support for other properties, such as events, may be added in the future.

Note: The abbreviated form <></> is not supported well by some front-end tools at present, and projects created with create-react-app may not be compiled. So it is normal to encounter this situation.

This is the end of this article about the introduction and detailed use of React Fragment. For more relevant React Fragment content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the connect decorator usage in react-redux @connect
  • ReactNative FlatList usage and pitfalls package summary
  • React Native implements simple login function (recommended)
  • Detailed explanation of React Native open source time date picker component (react-native-datetime)
  • Solution to the 404 problem of react-router browserHistory refresh page
  • How to use react-router4.0 to implement redirection and 404 functions
  • Detailed explanation of the redirection methods of each version of React routing
  • React build post-packaging and release summary

<<:  jenkins+gitlab+nginx deployment of front-end application

>>:  32 Typical Column/Grid-Based Websites

Recommend

MySQL 5.6.37 (zip) download installation configuration graphic tutorial

This article shares the download, installation an...

Copy and paste is the enemy of packaging

Before talking about OO, design patterns, and the ...

Vue calculated property implementation transcript

This article shares the Vue calculation property ...

The difference and use of json.stringify() and json.parse()

1. Differences between JSON.stringify() and JSON....

Native JS implements a very good-looking counter

Today I will share with you a good-looking counte...

Shorten the page rendering time to make the page run faster

How to shorten the page rendering time on the bro...

How to configure Hexo and GitHub to bind a custom domain name under Windows 10

Hexo binds a custom domain name to GitHub under W...

Implementation of CentOS8.0 network configuration

1. Differences in network configuration between C...

CSS3 realizes the childhood paper airplane

Today we are going to make origami airplanes (the...

Detailed explanation of MySQL startup options and system variables examples

Table of contents Boot Options Command Line Long ...

Configure Java development environment in Ubuntu 20.04 LTS

Download the Java Development Kit jdk The downloa...

Teach you to connect to MySQL database using eclipse

Preface Since errors always occur, record the pro...