EN
React - return multiple elements from component
3 points
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:
- By returning an array of elements,
- By using
React.Fragment
(empty tag).
It is necessary just to return array of React components from compoent.
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => [
6
<p key="1">React element</p>,
7
<p key="2">React element</p>,
8
<p key="3">React element</p>,
9
];
10
11
const root = document.querySelector('#root');
12
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.
React introduced simple way to use create elements that are not added to final DOM - the way is called fragments.
Check below practical examples:
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => (
6
<>
7
<p>React element</p>
8
<p>React element</p>
9
<p>React element</p>
10
</>
11
);
12
13
const root = document.querySelector('#root');
14
ReactDOM.render(<App />, root );
or
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => (
6
<React.Fragment>
7
<p>React element</p>
8
<p>React element</p>
9
<p>React element</p>
10
</React.Fragment>
11
);
12
13
const root = document.querySelector('#root');
14
ReactDOM.render(<App />, root );