Go Back

React: How To Return Multiple Elements in JSX

Posted on 2018-11-21

Sometimes you have a component, that only has to return HTML or JSX:

const Heading = () => {
  return (
    <h1>Heading</h1>
    <h4>Subheading</h4>
  )
}

This won't run as expected, because a component can only return one parent element. But we can use a div around it:

const Heading = () => {
  return (
    <div>
      <h1>Heading</h1>
      <h4>Subheading</h4>
    </div>
  )
}

This will work, but we don't want to clutter our code with useless div elements.

Solution

Instead, you can use Fragment:

const Heading = () => {
  return (
    <Fragment>
      <h1>Heading</h1>
      <h4>Subheading</h4>
    </Fragment>
  )
}

You can also use <> instead of Fragment