React fragments are a way to group a list of children without adding additional DOM nodes. Fragments allow you to return multiple elements from a component's render method without wrapping them in an extra element.
Using the React.Fragment
component: You can use the React.Fragment
component to group a list of children without adding additional DOM nodes. This can be useful if you need to support older versions of React that don't support the JSX fragment syntax (<></>)
.
import React from "react";
function List(props) {
return (
<React.Fragment>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</React.Fragment>
);
}
function App() {
return <List />;
}
Using the JSX fragment syntax (<></>)
: In newer versions of React, you can use the JSX fragment syntax (<></>)
to group a list of children without adding additional DOM nodes. This is a shorter and more concise syntax than using the React.Fragment
component.
import React from "react";
function List(props) {
return (
<>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</>
);
}
function App() {
return <List />;
}
Fragments are useful because they allow you to group a list of children without adding additional DOM nodes, which can make your code more efficient and easier to read.