What are React fragments used for?
Experience Level: Junior
Tags: React
Answer
React fragments are used to group a list of children elements without adding an extra node to the DOM. They are a way to return multiple elements from a component's render method. Fragments are useful when we want to return a list of elements, but we don't want to add an extra node to the DOM. This is because React requires that a component's render method returns a single node.
For example, let's say we have a component that returns a list of items. We could use a fragment to group the list items without adding an extra node to the DOM. Here's an example:
function ItemList() {
return (
<>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</>
);
}
In this example, we're using an empty fragment to group the list items. This will return a list of three items without adding an extra node to the DOM.
Fragments can also be useful when we're rendering a list of components. In this case, we can use a fragment to group the components without adding an extra node to the DOM. Here's an example:
function ItemList() {
const items = ['Item 1', 'Item 2', 'Item 3'];
return (
<>
{items.map(item => (
<Item key={item} item={item} />
))}
</>
);
}
function Item({ item }) {
return <li>{item}</li>;
}
In this example, we're using a fragment to group the list of `Item` components. This will return a list of three `Item` components without adding an extra node to the DOM.Related React job interview questions
How do you render lists in React?
React JuniorWhy do we need keys for React lists?
React JuniorHow do you pass data to React components?
React JuniorHow is React shadow DOM different than virtual DOM?
React JuniorWhat is React virtual DOM?
React Junior