Fragment in React.js

React JSJavascript LibraryFront End Technology

Most of the times we need to return multiple elements from a component. React Fragment helps in returning multiple elements. The other alternative is to use a html element like div to wrap them. But using extra html node can cause some semantic issues.

Example of React.Fragment

render() {
   return (
      <React.Fragment>
      <ElementA />
      <ElementB />
      <ElementC />
      </React.Fragment>
   );
}
The short syntax is <>:
render() {
   return (
      <>
         <ElementA />
         <ElementB />
         <ElementC />
      </>
   );
}

Understanding the problem if React Fragment is not used −

Suppose we create a table −

class ExampleTable extends React.Component {
   render() {
      return (
         <table>
            <tr>
               <ExampleColumns />
            <tr>
         </table>
      );
   }
}
class ExampleColumns extends React.Component {
   render() {
      return (
         <div>
            <td>col 1</td>
            <td>col 2</td>
         </div>
      );
   }
}

The actual syntax will include the div which we have added in the return statement of columns.

<table>
   <tr>
      <div>
         <td>col 1 </td>
         <td>col 2</td>
      </div>
   </tr>
</table>

Now, table tag is containing a div tag which is breaking the semantic of the html. So to avoid this we can simply replace the div with React.Fragment or in short <>

class ExampleColumns extends React.Component {
   render() {
      return (
         <>
            <td>col 1</td>
            <td>col 2</td>
         </>
      );
   }
}

We can use the fragment in iterating of list as well.

props.myMessages.map(message => (
   // Without the `key`, React will fire a key warning
   <React.Fragment key={message.id}>
      <dt>{message.title}</dt>
      <dd>{message.text}</dd>
   </React.Fragment>
))
raja
Published on 05-Sep-2019 07:48:28
Advertisements