A common pattern in React is for a component to return multiple elements. Fragments allow you to group sublists without adding additional nodes to the DOM.
Example: The Table component has a nested subcomponent Columns
class Table extends React.Component { render() { return ( <table> <tr> <Columns /> </tr> </table> ); }}Copy the code
Multiple elements need to be returned for the rendered HTML to be valid. If the
If the parent div is used in render(), the generated HTML will be invalid.
class Columns extends React.Component { render() { return ( <div> <td>Hello</td> <td>World</td> </div> ); }}Copy the code
Render and get one
<table>
<tr>
<div>
<td>Hello</td>
<td>World</td>
</div>
</tr>
</table>
Copy the code
Fragments solve this problem.
class Columns extends React.Component { render() { return ( <React.Fragment> <td>Hello</td> <td>World</td> </React.Fragment> ); }}Copy the code
This will output correctly
<table>
<tr>
<td>Hello</td>
<td>World</td>
</tr>
</table>
Copy the code
Phrasal: We can use a new, shorter syntax to declare Fragments. It looks like an empty label
class Columns extends React.Component { render() { return ( <> <td>Hello</td> <td>World</td> </> ); }}Copy the code
We can use <> just like any other element, except that it does not support keys or attributes.
Wish you all become stronger!