Skip to content
Middle+5 views

What is a React Fragment, and which props can it accept?

Practice

Asked at

AI answer

React.Fragment groups multiple children without adding an extra DOM node. This is useful, for example, when a component needs to return several adjacent elements:

return (
  <React.Fragment>
    <h2>Title</h2>
    <p>Text</p>
  </React.Fragment>
);

The shorthand syntax <>...</> is equivalent to Fragment, but does not allow props to be passed. To use a Fragment with a key, use the full syntax: <React.Fragment key={item.id}>...</React.Fragment>. key is useful, for example, when returning multiple elements from map; Fragment does not support arbitrary props. In special experimental/Canary builds of React, ref may also be available on Fragment.