Fragment
TheFragment component allows you to group multiple children without adding an extra DOM element.
Type
Fragment is represented by the symbol Symbol.for('react.fragment') (the value of REACT_FRAGMENT_TYPE in React’s source).
Short Syntax
You can use<></> as shorthand for <Fragment></Fragment>:
- Is more concise and commonly used
- Does not support keys or other attributes
- Is functionally identical to
<Fragment>
Usage
Returning Multiple Elements
Fragments are most commonly used to return multiple elements from a component:<div> or other element, adding an extra node to the DOM:
Avoiding Wrapper Elements
Fragments are especially useful when wrapper elements would break styling or semantics: Table rows:With Text and Elements
Fragments can contain any mix of elements and text:Conditional Rendering
Fragments work well with conditional rendering:Using Keys with Fragments
When you need to provide akey to a fragment (e.g., when mapping over an array), you must use the explicit <Fragment> syntax:
The short syntax
<></> does not support keys or any other attributes. If you need to add a key, you must use the explicit <Fragment key={...}> syntax.When to Use Fragments
Use Fragments When:
1. You need to return multiple elements from a component:Don’t Use Fragments When:
1. You need to apply styles or event handlers:Fragment vs. Array
Before fragments existed, people used arrays to return multiple elements:- No need to add keys to every element
- Cleaner, more readable syntax
- Works better with TypeScript typing
- No commas between elements
Example: Complex Fragment Usage
createElement with Fragments
You can create fragments programmatically usingcreateElement:
Performance:Fragments have no performance overhead compared to using wrapper
<div> elements. In fact, they can be slightly more performant because:- They don’t create DOM nodes
- The React reconciliation algorithm has less work to do
- There are fewer elements in the DOM tree