
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
ReactJS Fragments
While building a ReactJS application, all the JSX code needed to be wrapped down inside a parent tag.
ReactJS Fragments were introduced with React 16.2 version to remove the need to define an extra <div> tag which also takes extra memory.
Without Fragments
The following sample code shows how to create a simple React application without React Fragments.
Example
App.jsx
import React from 'react'; class App extends React.Component { render() { return ( <div> <h2>TutorialsPoint</h2> <p>Simply Easy Learning</p> </div> ); } } export default App;
Output
Using Fragments
In the above example, we have to use an extra <div> tag to wrap the children JSX elements. So with ReactJS 16.2 version, we will use the React.Fragment which will remove the need to use an extraneous <div> tag.
Example
App.jsx
import React from 'react'; class App extends React.Component { render() { return ( <React.Fragment> <h2>TutorialsPoint</h2> <p>Simply Easy Learning</p> </React.Fragment> ); } } export default App;
Output
Shorthand of Fragment
We can also use <>, instead of React.Fragment but this shorthand syntax does not accept key attributes.
Example
import React from 'react'; class App extends React.Component { render() { return ( <> <h2>TutorialsPoint</h2> <p>Simply Easy Learning</p> </> ); } } export default App;
Output
Advertisements