How to render Multiple Elements

How to render Multiple Elements

Table of contents

No heading

No headings in the article.

There are several ways to render multiple elements in React. Here are two common methods:

  1. Using a parent element: Wrap the multiple elements inside a parent element, such as a div, and return them from the component's render() method. Here's an example:

     import React from 'react';
    
     function MyComponent() {
       return (
         <div>
           <h1>Hello, World!</h1>
           <p>This is a paragraph.</p>
           <button>Click me!</button>
         </div>
       );
     }
    

    In the above example, the MyComponent function returns multiple elements wrapped inside a div element. These elements can include other React components, HTML tags, or a combination of both.

    It's important to note that when rendering multiple elements, React requires that they have a unique key prop. This helps React identify each element and efficiently update the DOM when changes occur. You can set a key prop by passing a unique identifier, such as an ID or index, to the component or element.

  2. Using React Fragments: Wrap the multiple elements inside a React Fragment, which allows you to group a list of children without adding extra nodes to the DOM. Here's an example:

ReactDOM.render(
  <React.Fragment>
    <h1>Element</h1>
    <h2>Element</h2>
    <h3>Element</h3>
    <h4>Element</h4>
    <h5>Element</h5>
    <h6>Element</h6>    
 </React.Fragment>,
    document.getElementById("root")
  );

The shorthand for the fragment is-

ReactDOM.render(
  <>
    <h1>Element</h1>
    <h2>Element</h2>
    <h3>Element</h3>
    <h4>Element</h4>
    <h5>Element</h5>
    <h6>Element</h6>    
 </>,
    document.getElementById("root")
  );

Fragments are useful in situations where you need to return multiple elements from render but don't want to add unnecessary extra nodes to the DOM. This can make your code more readable, and also help improve performance.

Without fragment-

With fragment-