Render Multiple Elements using React.Fragment and the JSX Fragment Syntax <> in React 16.2

Nik Graf
InstructorNik Graf

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

With React 16 it is possible now to return an Array of elements.

In React 16.2 support for fragments was added. It's a convenient way to return multiple children from a component’s render method.

Instructor: [00:00] You can see an app rendering a list of fruits. We can extend this list using a fruits' component returning an array.

[00:17] In React 16.2, the Fragment component was added. We can access it using React.Fragment, and use it to wrap a set of elements.

[00:28] When using Fragment, no DOM element is rendered, and behaves as if your work return an array of elements. One definite benefit here is that you can omit the keys.

[00:41] As you can see, all fruits show up. By inspecting the DOM, we can see all of them are rendered inside the same unordered list element. If desired, we can also import Fragment from React and use it directly.

[00:58] To make the offering experience as convenient as possible, the reacting addicts from tactical sugar for Fragment to JSX, since that of using React.Fragment, or importing it, we can simply use this syntax. Same as our shell before, since it automatically desugars to React.Fragment.

[01:17] In case you need a kit Fragment, we have to use Fragment directly. You define a glossary component, rendering for each item, a pair of HTML elements -- dt and td. To avoid wrapping elements like a div, we use a fragment. Because we provide a key, we have to type out "Fragment."

~ 4 years ago

Because they don't require a "key", does that mean react does not track them the same as an list item with a key?

Nik Graf
Nik Grafinstructor
~ 4 years ago

@spencer From what I understood components inherently get tracked correct and that's why keys are not needed.