Languages
[Edit]
EN

React - return multiple elements from component

3 points
Created by:
Dirask Community
6240

In this article we would like to show you how to return multiple elements from a component in React.

Below runnable examples show two ways how to do it:

  1. By returning an array of elements,
  2. By using React.Fragment (empty tag).

1. Using array notation

It is necessary just to return array of React components from compoent.

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => [
  <p key="1">React element</p>,
  <p key="2">React element</p>,
  <p key="3">React element</p>,
];

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Note: 
We have to add a key to each element to avoid warnings - keys help React to manage DOM changes in optimal way.

2. Using React.Fragment

React introduced simple way to use create elements that are not added to final DOM - the way is called fragments.

Check below practical examples:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => (
  <>
    <p>React element</p>
    <p>React element</p>
    <p>React element</p>
  </>
);

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

or

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => (
  <React.Fragment>
    <p>React element</p>
    <p>React element</p>
    <p>React element</p>
  </React.Fragment>
);

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

ReactJS

React - return multiple elements from component
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join