React Fragments provide a way to group multiple elements without adding an extra node to the DOM. Before the introduction of React Fragments, if you wanted to return multiple elements from a component without a parent wrapper, you had to use a wrapper element (like a <div>
), which could affect the structure of your HTML and add unnecessary elements to the DOM.
React Fragments allow you to group multiple elements without introducing a new parent element in the rendered HTML. You can use the shorthand syntax <>...</>
or <React.Fragment>...</React.Fragment>
to create a fragment.
Using React Fragments:
Shorthand Syntax:
import React from 'react';
const MyComponent = () => {
return (
<>
<p>Element 1</p>
<p>Element 2</p>
</>
);
};
Long Syntax:
import React from 'react';
const MyComponent = () => {
return (
<React.Fragment>
<p>Element 1</p>
<p>Element 2</p>
</React.Fragment>
);
};
Key Features of React Fragments:
- No Extra DOM Element:
- Fragments don’t create an extra DOM element in the rendered output. They allow you to group elements without affecting the structure of the HTML.
- Avoiding Unnecessary Wrappers:
- When you need to return multiple elements from a component, fragments help you avoid introducing wrapper elements that might interfere with CSS or cause unwanted side effects.
- Improving Readability:
- Fragments make your JSX code more concise and readable, especially when dealing with components that return multiple elements.
- Support for Keys:
- Like regular elements, fragments can also have keys, which is useful when mapping over an array of elements.
const MyList = ({ items }) => {
return (
<>
{items.map((item) => (
<React.Fragment key={item.id}>
<p>{item.text}</p>
</React.Fragment>
))}
</>
);
};
React Fragments provide a clean and concise way to group elements in React components, especially when you need to return multiple elements without introducing unnecessary parent nodes in the DOM.