Published on

What is a Fragment `<></>`?

Authors
  • avatar
    Name
    hwahyeon
    Twitter

Fragment is a tool in React used to group multiple elements without adding unnecessary DOM elements. It allows developers to wrap JSX elements without creating additional parent nodes in the DOM.

Key Features:

1. Avoiding Unnecessary DOM Elements

Using Fragment, you can group elements without adding extra DOM nodes like <div> or <span>.

Example:

return (
  <React.Fragment>
    <h1>Hello</h1>
    <p>World!</p>
  </React.Fragment>
)

Output in the DOM:

<h1>Hello</h1>
<p>World!</p>

2. Syntax Shorthand

Instead of writing <React.Fragment>, you can use the shorthand <> and </> for simpler code. Both work the same way but note the limitations below.

Example:

function App() {
  return (
    <>
      <h1>Hello</h1>
      <p>World!</p>
    </>
  )
}

3. Supports key Attribute

React.Fragment supports attributes like key, which are essential for efficient list rendering in React. However, the shorthand <> does not support attributes and must be replaced with <React.Fragment> in such cases.

Example:

function List() {
  const items = ['Apple', 'Banana', 'Cherry']
  return (
    <>
      {items.map((item, index) => (
        <React.Fragment key={index}>
          <li>{item}</li>
        </React.Fragment>
      ))}
    </>
  )
}

Version Dependency

Fragment and its shorthand <> are supported in React 16.2 and later.