Rendering Multiple Elements in React JS Components
There are three ways to return multiple element from a component:
- Enclose multiple elements under div tag
- Use array to return multiple elements
- Use React.Fragment node to enclose multiple html/JSX elements
1-Enclose multiple elements under div tag:
Example:
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div>
<h1>This is our first component</h1>
<p>Message from first component</p>
</div>
);
}
export default App;
Downsize of this approach is that extra div tag will be render on browser if we see it via Page source on browser.
2- Use array to return multiple elements:
Example
import logo from './logo.svg';
import './App.css';
function App() {
return (
[
<h1>This is our first component</h1>,
<p>Message from first component</p>
]
);
}
export default App;
It is allowed in react versions >=16.
3- Use React.Fragment node to enclose mulitple html/JSX elements:
Example:
import logo from './logo.svg';
import './App.css';
function App() {
return (
<React.Fragment>
<h1>This is our first component</h1>
<p>Message from first component</p>
</React.Fragment>
);
}
export default App;
Another alternate way to define is to create note without mentioning name like <> </>
Example:
import logo from './logo.svg';
import './App.css';
function App() {
return (
<>
<h1>This is our first component</h1>
<p>Message from first component</p>
</>
);
}