When returning multiple elements from a component’s render method, they must be wrapped in a single parent DOM node:
This extra wrapper
<div> in the DOM is often unwanted. Enter React fragments - a way to group elements without adding extra nodes.
The simplest fragment syntax is:
<></> syntax declares a React fragment. Fragments let you skip the wrapper
Fragments can also be keyed to give child elements a context:
Keyed fragments are handy for list items that need a context.
Fragments were introduced to reduce extra DOM nodes. Some benefits are:
- Avoid wrapper nodes in DOM tree
- Semantically group components together
- Key list items without adding wrappers
This improves render efficiency and semantics.
- Use short syntax for inline component groups
- Key fragments to provide list item context
- Prefer fragments over wrapper divs
- Don’t overuse - try to keep components logically grouped
Fragments are a tool for cleaner, more readable component trees.
- Fragments let you group elements without a DOM node
- Provides shorter syntax vs wrapper divs
- Keyed fragments provide context for lists
- Improves render efficiency and semantics
- Use judiciously according to use case
React fragments are a key tool for building component hierarchies. No more mystery boxes!