Languages
[Edit]
EN

React - how to use fragments

0 points
Created by:
sienko
743

In this article, we would like to show you how to use fragments in React.

Quick solution:

 

To render multiple elements in React, we need to wrap them with a <div> because components can only return a single element. However, there are situations when we don't want to create an additional element in the DOM. That's when we can use React fragments.

Below example presents a situation when we want to externally implement columns for our table. In order for TableColumns to render multiple elements, we have to render our cells inside one element. Wrapping them with a <div> will lead to errors, so we use <React.Fragment> instead.

Note:

We can also use React fragments short syntax <>  </> (an empty tag) to wrap the elements.

Runnable example:

short syntax example:

References

Edit

Alternative titles

  1. React - fragments example
  2. React - wrap components with empty tag
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join