How to Use Fragments in React: Syntax and Examples
In React, use
Fragments to group multiple elements without adding extra nodes to the DOM. You can use <React.Fragment> or the shorthand <></> to wrap elements inside a component.Syntax
React fragments let you group multiple elements without adding extra HTML tags. You can use either the full syntax <React.Fragment> or the shorthand <></>. The shorthand cannot accept keys or attributes, but the full syntax can.
jsx
function Example() { return ( <> <p>First element</p> <p>Second element</p> </> ); }
Example
This example shows a component returning two paragraphs wrapped in a fragment. The fragment prevents adding an extra wrapper element in the HTML output.
jsx
import React from 'react'; import { createRoot } from 'react-dom/client'; function Greeting() { return ( <> <h1>Hello!</h1> <p>Welcome to React fragments.</p> </> ); } const container = document.getElementById('root'); const root = createRoot(container); root.render(<Greeting />);
Output
<h1>Hello!</h1><p>Welcome to React fragments.</p>
Common Pitfalls
One common mistake is trying to add attributes like key to the shorthand fragment <></>, which is not allowed. Use <React.Fragment key="unique"> instead when keys are needed, such as in lists.
Another pitfall is wrapping elements unnecessarily with extra <div> tags, which fragments help avoid.
jsx
/* Wrong: Adding key to shorthand fragment (causes error) */ function List() { return ( <> <li key="1">Item 1</li> <li key="2">Item 2</li> </> ); } /* Right: Use React.Fragment with key */ function ListCorrect() { return ( <> <React.Fragment key="1"><li>Item 1</li></React.Fragment> <React.Fragment key="2"><li>Item 2</li></React.Fragment> </> ); }
Quick Reference
- <React.Fragment>: Full syntax, supports keys and attributes.
- <></>: Shorthand syntax, no keys or attributes.
- Use fragments to avoid extra wrapper elements in the DOM.
- Fragments help keep your HTML clean and your React components simple.
Key Takeaways
Use React fragments to group multiple elements without extra DOM nodes.
The shorthand fragment syntax <>...> is simple but cannot have keys or attributes.
Use when you need to add keys, especially in lists.
Fragments help keep your HTML output clean and avoid unnecessary wrappers.
Avoid adding keys to shorthand fragments to prevent errors.