27

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?

0

4 Answers 4

24

Official document says

Using array notation has has some confusing differences from normal JSX:

  1. Children in an array must be separated by commas.

  2. Children in an array must have a key to prevent React’s key warning.

  3. Strings must be wrapped in quotes.

So to make it simple, React provides Fragment component that can be used in place of arrays.

Consider how we can wrap multiple children using array

render() {
 return [
  "Some text.",
  <h2 key="heading-1">A heading</h2>,
  "More text.",
  <h2 key="heading-2">Another heading</h2>,
  "Even more text."
 ];
}

And how it can be achieved using Fragments.

render() {
  return (
    <Fragment>
      Some text.
      <h2>A heading</h2>
      More text.
      <h2>Another heading</h2>
      Even more text.
    </Fragment>
  );
}

Taken directly from official document.

Fragments can be written as below aswell.

render() {
      return (
        <>
          Some text.
          <h2>A heading</h2>
          More text.
          <h2>Another heading</h2>
          Even more text.
        </>
      );
    }
7

There are two major advantages of using Fragments over array in return statement

  1. Simplistic syntax similar to Other components so that you don't have to worry about return comma separated values, wrapping strings in quotes etc
  2. Fragments can take attribute such as key which is often important when you are returning data from within map. You can't do that using an array.

Example

const ReturnFragments = () => {
  const items = list.map((item) => {
    <React.Fragment key={item.id}>
      <div key={1}>Item 1</div>
      <div key={2}>Item 2</div>
      <div key={3}>Item 3</div>
    </React.Fragment>
   })
  return items
}
7

Fragments and arrays are intended to address different use cases and behave differently in one important way.

Fragments will not warn if you omit a key property, while arrays will.

If your component returns several static children, return a fragment.

<Fragment>
  <li>One advantage of our product is lorem</li>
  <li>Another is ipsum!</li>
</Fragment>

If your component returns dynamically generated children, return an array.

items.map(item => <li key={item}>{item}</li>);

I am paraphrasing the maintainers' responses to an issue I opened in the React repo about a similar question. I highly recommend reading it for more detail: https://github.com/facebook/react/issues/12776

-2

When you create a new component, the render method needs to return one and only one element so usually it's a wrapper of many elements, instead of creating a useless div to the dom, you can use the fragment component.

Quote from React Fragments docs :

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

Without Fragments

    render() {
      return {
       <div> ---> Useless root
          <div>fake</div>
          <div>fake</div>
          <div>fake</div>
       </div>
     }
}

With Fragments

  render() {
      return {
       <React.Fragment> ----> Not rendered to the DOM
          <div>fake</div>
          <div>fake</div>
          <div>fake</div>
       </React.Fragment>
     }
   }
2
  • 5
    That's not actually true in React now, I can return a array of JSX elements, as shown in the <ReturnArray/> above
    – Sean
    Commented Mar 19, 2019 at 8:37
  • That's because they're wrapped in the array, try rendering them individually and it will not work.
    – S.Haviv
    Commented Mar 19, 2019 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.