The React Fragment: Creating Invisible HTML Tags
In React, when you want to return more than one element from a component, you usually wrap them in a div
to satisfy the requirement of returning a single element. However, this approach adds an unnecessary div
to the output. To avoid this, you can use React.Fragment
.
Here’s an example of how to use React.Fragment
:
1 | import React, { Component, Fragment } from 'react'; |
In recent releases of React (and Babel 7+), there is also a shorthand syntax available using <>
and </>
for React.Fragment
:
1 | import React, { Component, Fragment } from 'react'; |
Using React.Fragment
or the shorthand syntax <></>
allows you to group multiple elements without the need for an additional container tag like div
.
tags: [“React”, “React Fragments”]