React: React.Fragment vs array

ghz 6months ago ⋅ 57 views

React: <React.Fragment> vs array

I was reading the React doc and get confused by the topic Fragments. Since we can basically return an array in React, in what situation would one need <Fragements />?

Here is a code sample:

const ReturnArray = () => {
  const items = [
    <div key={1}>Item 1</div>,
    <div key={2}>Item 2</div>,
    <div key={3}>Item 3</div>,
  ]
  return items
}

const ReturnFragments = () => {
  const items = 
    <React.Fragment>
      <div key={1}>Item 1</div>
      <div key={2}>Item 2</div>
      <div key={3}>Item 3</div>
    </React.Fragment>

  return items
}

I think they are the same.

Most existing topics talk about "key warning issues" like this on github, but I just want to know the use cases of <Fragments />


Edit:

Please tell me if there is anything ambiguous.

To be specific:

Please explain the difference between <ReturnArray /> and <ReturnFragments />. They both return multiple elements without useless <div> tag. Why bother using the extra <React.Fragment /> part?

Answers

The confusion between using arrays and <React.Fragment> (or the shorthand <> </> syntax for fragments) in React revolves around understanding the differences in their use cases and how React handles these elements under the hood.

Understanding <React.Fragment>

Purpose: <React.Fragment> (or its shorthand <> </>) is used to group multiple elements without adding extra nodes to the DOM.

Key Points:

  1. No Extra DOM Nodes: When you return an array of elements in React, each element must have a unique key, and they are typically wrapped in a container like a <div> to satisfy the single parent element requirement in JSX.

    • Example with array:
      const ReturnArray = () => {
        const items = [
          <div key={1}>Item 1</div>,
          <div key={2}>Item 2</div>,
          <div key={3}>Item 3</div>,
        ];
        return items;
      };
      
      In this case, ReturnArray would return an array of <div> elements, which would need to be wrapped in a parent <div> or another element.
  2. Fragment as a Wrapper: <React.Fragment> allows you to group multiple elements without introducing an extra DOM node. This is particularly useful in cases where you want to avoid adding unnecessary nodes to the rendered output but still need a way to group elements.

    • Example with <React.Fragment>:
      const ReturnFragments = () => {
        return (
          <React.Fragment>
            <div key={1}>Item 1</div>
            <div key={2}>Item 2</div>
            <div key={3}>Item 3</div>
          </React.Fragment>
        );
      };
      
      This approach doesn't add any extra nodes to the DOM, unlike wrapping elements in a <div>.
  3. Array vs. Fragment:

    • Array: Useful for returning multiple elements but requires a parent wrapper element (like <div>) to group them, which adds an extra node to the DOM.
    • Fragment: Allows you to group elements without adding an extra node to the DOM, providing cleaner JSX syntax and better performance in some cases.

Use Cases for <React.Fragment>

  • Lists and Tables: When mapping over arrays to render lists or table rows, using <React.Fragment> can avoid unnecessary <div> wrappers around each item.

  • Conditional Rendering: When you have multiple elements to conditionally render, <React.Fragment> can help group these elements cleanly without affecting the DOM structure.

  • Performance Considerations: In scenarios where rendering performance is critical, avoiding extra DOM nodes with <React.Fragment> can be beneficial.

Summary

While both returning arrays of elements and using <React.Fragment> can achieve similar outcomes of rendering multiple elements, <React.Fragment> offers a cleaner syntax without introducing extra nodes to the DOM. It's particularly useful in cases where you want to maintain a clean JSX structure and improve performance by minimizing unnecessary DOM nodes.

In your provided example, both <ReturnArray /> and <ReturnFragments /> render multiple elements, but <ReturnFragments /> using <React.Fragment> avoids adding an unnecessary wrapping <div> to the rendered output, thus keeping the DOM structure cleaner. This can be especially beneficial in larger applications where minimizing DOM nodes can lead to better performance and maintainability.