JavaScript

React Fragment

React Fragment is a feature in React that allows developers to group a list of children without adding extra nodes to the DOM. This is particularly useful for situations where you want to return multiple elements from a component without having to add an extra wrapper element.

Before the introduction of React Fragment, developers would often use a div or a span to group multiple elements. However, this would add an extra node to the DOM, which could cause unnecessary re-renders and negatively impact the performance of the application.

To create a fragment, you can use the React.Fragment component, or you can use the short syntax <> and </>. Here's an example using the long syntax:

Example 1: Long syntax

Functional
Class
import React from 'react';

function MyComponent() {
return (
<React.Fragment>
<h1>Heading</h1>
<p>Paragraph</p>
</React.Fragment>
);
}
Copy

And here's the same example using the short syntax:

Example 2: Short syntax

Functional
Class
import React from 'react';

function MyComponent() {
return (
<>
<h1>Heading</h1>
<p>Paragraph</p>
</>
);
}
Copy

One important thing to note is that short syntax fragments cannot have a key or other props, so you cannot use them to wrap a list of elements and pass a key prop to each element. Instead, you should use the long syntax like so:

Example 3: Keys

Functional
Class
import React from 'react';

function App() {
const items = ['item 1', 'item 2', 'item 3'];

return (
<ul>
{items.map((item, index) => (
<React.Fragment key={index}>{item}</React.Fragment>
))}
</ul>
);
}

export default App
Copy

Fragments can be useful for reducing the number of wrapper elements in your code, which can make it easier to read and debug.

In an interview, you may be asked about when and why you would use fragments, as well as how they differ from other methods of grouping elements in React, such as using an additional wrapper element or an array. You may also be asked to compare and contrast fragments with other ways of grouping elements, such as using the div element or using a div element with a unique class name for styling purposes.