- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Fragment in React.js
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> ))
- Related Articles
- SVG morphing in React JS
- Adding Lottie animation in React JS
- SVG drawing in React JS frontend
- Creating a Particle Animation in React JS
- Creating a Customizable Modal in React JS
- Creating animated loading skeletons in React JS
- Drawing arrows between DOM elements in React JS using react-archer
- Creating an Airbnb Rheostat Slider in React JS
- Creating a Rich Text Editor in React JS
- Device Detection and Responsive Design in React JS
- Using pointer light for better lighting in React JS with React-Three-Fiber
- SVG zoom-in and zoom-out in React JS
- How to make a resizable element in React JS
- Making a timer in React JS using reactspring animation
- Creating an Excel-like data grid in React JS
- Drag and Drop a File feature in React JS

Advertisements