Skip to content

Latest commit

 

History

History
51 lines (38 loc) · 1.47 KB

11.ReactFragments.md

File metadata and controls

51 lines (38 loc) · 1.47 KB

Eliminate Unnecessary Wrapper Elements with React Fragments

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.

There are two ways you can use fragments in React:

1. React.fragment

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 />;
}

2. <></>

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.