← flaviocopes.com

How to return multiple elements in JSX

Published Jan 24 2019

Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! ✨

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.



I write books for developers 👇🏼

© 2023 Flavio Copes Flavio Copes made in Italy 🇮🇹 using Notion to Site Notion to Site