Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: <React.Fragment> vs array

Tags:

reactjs

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?

like image 516
Sean Avatar asked Mar 19 '19 08:03

Sean


People also ask

When should I use React fragment?

React Fragments allow you to wrap or group multiple elements without adding an extra node to the DOM. This can be useful when rendering multiple child elements/components in a single parent component.

Why we use React fragment instead of DIV?

Therefore, React fragments are better than the 'div' tags. With React Fragment, you can render multiple elements of a component without adding extra div tags. We can write cleaner, more readable code with React Fragments. It takes up less memory and renders components faster. Each component is rendered as expected.

Is React children an array?

React. Children. toArray returns the children opaque data structure as a flat array with keys assigned to each child.

Is <> same as React fragment?

<> is the shorthand tag for React. Fragment which allows us to group a list of elements without wrapping them in a new node. The only difference between them is that the shorthand version does not support the key attribute.


3 Answers

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.
        </>
      );
    }
like image 88
G_S Avatar answered Oct 20 '22 14:10

G_S


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
}
like image 37
Shubham Khatri Avatar answered Oct 20 '22 16:10

Shubham Khatri


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

like image 4
Alex Ryan Avatar answered Oct 20 '22 14:10

Alex Ryan