How to return multiple elements in JSX

How to solve the limitations of JSX when multiple elements must be returned from the component

When writing JSX in React, there is a caveat: you must return a parent item. No more than one.

For example, this is not possible:

const Pets = () => {
  return (
    <Dog />
    <Cat />
  )
}

A "classic" way to solve this problem is to wrap components and other HTML elements indiv:

const Pets = () => {
  return (
    <div>
      <Dog />
      <Cat />
    </div>
  )
}

However, this brings up a problem-an HTML element is introduced just to make our JSX work, and is not necessary in the generated HTML, but this is the end of it.

One solution is to return an array of JSX elements:

const Pets = () => {
  return [
      <Dog />,
      <Cat />
  ]
}

Another solution is to use Fragment, which is a relatively new React feature that can solve the problem for us:

const Pets = () => {
  return (
    <Fragment>
      <Dog />
      <Cat />
    </Fragment>
  )
}

It's likedivThe elements we added before will not appear in the HTML results presented to the browser. Win-win.

Download mine for freeResponse Handbook


More response tutorials: