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

Specific use of Linux gcc command

01. Command Overview The gcc command uses the C/C...

The correct way to migrate MySQL data to Oracle

There is a table student in the mysql database, i...

MySQL 8.0.21 installation and configuration method graphic tutorial

Record the installation and configuration method ...

Summary of several error logs about MySQL MHA setup and switching

1: masterha_check_repl replica set error replicat...

Vue uses the method in the reference library with source code

The official source code of monaco-editor-vue is ...

Understanding of CSS selector weight (personal test)

Copy code The code is as follows: <style type=...

Configure Java development environment in Ubuntu 20.04 LTS

Download the Java Development Kit jdk The downloa...

How to manage multiple projects on CentOS SVN server

One demand Generally speaking, a company has mult...

Linux kernel device driver kernel time management notes

/****************** * Linux kernel time managemen...

Summary of the differences between MySQL storage engines MyISAM and InnoDB

1. Changes in MySQL's default storage engine ...

MySQL UNION operator basic knowledge points

MySQL UNION Operator This tutorial introduces the...

WeChat applet uses canvas to draw clocks

This article shares the specific code of using ca...

Troubleshooting the cause of 502 bad gateway error on nginx server

The server reports an error 502 when synchronizin...