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).
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 );