A common pattern in React is to return multiple elements for a component. You must have written a lot of divs and spans to wrap multiple elements, creating unnecessary nesting and adding to the browser’s rendering stress. Fragments allow you to aggregate lists of child elements without adding additional nodes.

Version 15

Previously, the render function had to return a root node, otherwise an error would be reported. To satisfy this rule, I wrapped the array in a div with no style whatsoever.

import React from 'react'; Export default function () {return (<div> <div> step 01</div> <div> step 02</div> <div> Step 03</div> <div> step 04</div> </div> ); }Copy the code

The code looks like this

The render function allows you to return an array 👍

React 16: Render supports returning arrays. This feature can already avoid unnecessary node nesting, small friends can use more.

import React from 'react'; Export default function () {return [div> step 01</div>, <div> step 02</div>, <div> step 03</div>, <div> step 04</div>]; }Copy the code

Fragments

What? You don’t like to write arrays, why not lazy ~~. Fortunately, React 16 provides us with Fragments. Fragments are similar to the

import React from 'react'; Export default function () {return (< react. Fragment> <div> step 01</div> <div> step 02</div> <div> step 03</div> <div> step 04</div> </React.Fragment> ); }Copy the code

Short form for Fragments<></>

This is pretty bad, but some of the front-end tools don’t support it very well, and the projects I created using create-React-app didn’t compile well. Try it out with an online editor.

import React from 'react'; Export default function () {return (<> <div> step 01</div> <div> step 02</div> <div> step 03</div> <div> step 04</div> </>); }Copy the code

<></>

The above

Now you’ve heard React Fragments 👏