What Are React Fragments? Complete Example Tutorial Guide

What Are React Fragments?

React Fragments let you group multiple elements without adding extra nodes to the DOM.
They help avoid unnecessary <div> wrappers and keep HTML cleaner.


Basic Syntax

<React.Fragment>
  <h1>Hello</h1>
  <p>Welcome to React</p>
</React.Fragment>

Or the shorthand:

<>
  <h1>Hello</h1>
  <p>Welcome to React</p>
</>

Example in a Component

function App() {
  return (
    <>
      <h1>My App</h1>
      <p>This is a paragraph.</p>
    </>
  );
}

✅ No extra nodes are added to the DOM.


When To Use Fragments

  • Return multiple elements from a component
  • Avoid unnecessary <div> or wrapper elements
  • Improve HTML structure and performance

Key Points

  • <Fragment> or <>...</> can be used
  • Can also pass key to <Fragment> in lists
  • Shorthand <>...</> cannot accept keys or attributes

Conclusion

React Fragments simplify JSX structure, prevent extra DOM nodes, and make components cleaner and more efficient.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *