React web applications are essentially component trees with branches – a component might render multiple components, which render more components on their own.

To build any kind of useful web application, you need to know how to render multiple components in React.

Common mistakes

Every React component uses the render() function to render components. The function has a return statement, which returns JSX code.

In JSX, you can invoke and render as many components as you’d like, as long as you follow one important rule: the render() function must return one element.

You can render multiple components in React, but make sure to put them in one container. React developers typically use <div> to wrap multiple components.

Since React v16.2, you can use React fragments as well.

These are even better than <div>, because they don’t create unnecessary HTML elements.

Let’s explore both ways to render multiple components – <div> as well as fragments.

Render multiple components in React – <div> vs <>

Let’s start with <div>, which is simpler. Even beginner web developers know what a <div> container is and what it does.

So, let’s imagine you have a JSX code with multiple components:

export default function App() {
  return (
      <Contact />
      <Form />
      <Footer />
  );
}

In this example, we are trying to render multiple components.

Problem is that they are not wrapped in one container, so React is going to throw an error.

render() function must return only one React element. The easy solution is to wrap all these components with one <div> element:

export default function App() {
  return (
 <div>
      <Contact />
      <Form />
      <Footer />
 </div>
  );
}

Adding these components to one <div> container should the error.

Use JSX fragment

Few years ago, React team introduced an easier and more efficient solution – JSX fragments.

You can use these to imitate a container to render multiple components and not get an error.

Syntax looks like an empty HTML element as well.

Let’s look at an example:

export default function App() {
  return (
    <>
      <Contact />
      <Form />
      <Footer />
   </>
  );
}

JSX fragments are better because they do not create unnecessary div elements in HTML.