Skip to content

How to return multiple elements in JSX

New Course Coming Soon:

Get Really Good at Git

How to workaround that the limitation that JSX has when having to return multiple elements from a component

When writing JSX in React, there’s one caveat: you must return one parent item. Not more than one.

For example, this is not possible:

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

One “classic” way to solve this is to wrap components and other HTML elements in a div:

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

However this introduces a problem - there’s an HTML element that was introduced just to make our JSX work, not necessary in the resulting HTML, but that’s where it ends into.

One solution is to to return an array of JSX elements:

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

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

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

it works like the div element we added before, but it’s not going to appear in the resulting HTML rendered to the browser. Win-win.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my React Beginner's Handbook
→ Read my full React Tutorial on The Valley of Code

Here is how can I help you: