Parent/Fragment
- In React apps, a component can only return a single element.
- To return multiple elements, we wrap them in a parent element or a fragment, which is represented by empty angle brackets.
Option 1 - div
- We're adding one extra element in the DOM
return (
<div>
<h1>List</h1>
<ul className="list-group">
<li className="list-group-item">An item</li>
<li className="list-group-item">A second item</li>
<li className="list-group-item">A third item</li>
<li className="list-group-item">A fourth item</li>
<li className="list-group-item">And a fifth one</li>
</ul>
</div>
);
Option 2 - Fragment
- Instead of additional element, you can use
Fragment
- Import fragment
import {Fragment} from "react";
return (
<Fragment>
<h1>List</h1>
<ul className="list-group">
<li className="list-group-item">An item</li>
<li className="list-group-item">A second item</li>
<li className="list-group-item">A third item</li>
<li className="list-group-item">A fourth item</li>
<li className="list-group-item">And a fifth one</li>
</ul>
</Fragment>
);
Option 3 - Empty angle bracket (Preferred)
- Telling react to use a fragment to wrap all this children
return (
<>
<h1>List</h1>
<ul className="list-group">
<li className="list-group-item">An item</li>
<li className="list-group-item">A second item</li>
<li className="list-group-item">A third item</li>
<li className="list-group-item">A fourth item</li>
<li className="list-group-item">And a fifth one</li>
</ul>
</>
);