Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

What is the use of Fragment in React ?

  • Last Updated : 10 Oct, 2021

In ReactJS, we render the JSX from the component with the help of a return statement whether written inside the functional component or inside the render function of class components. Now the point is that in javascript the return statement can only return one entity, So when we have to return the multiple elements from return statements we usually create the extra node. This extra node has some disadvantages hence to avoid them we use the React Fragment. 

Prerequisites: Knowledge of how to start and create react app, JSX in react, and Basic Knowledge of HTML DOM.

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

 

How does a component render?



After creating the react application do the following changes in index.js and app.js here we are only going to work with these two files. The index.js file is the main entry point and inside it, the App.js is being rendered at the root id of the DOM with the help of the render method. Inside App.js there exists only an h1 tag.

 

index.js




import React from 'react';
import ReactDOM from 'react-dom';
  
import App from './App';
  
ReactDOM.render(<App />, 
    document.getElementById('root'));

App.js




import React from 'react';
  
function App() {
  return (
    <h1>Hello There</h1>
  );
}
  
export default App;

Output:

What if we have to return two different elements at the same level in DOM?

In this case, we have to use the container i.e. div otherwise React will through an error that goes like “Adjacent JSX elements must be wrapped in an enclosing tag“.



App.js




import React from 'react';
  
function App() {
  return (<div>
    <h1>Hello, There</h1>
    <h2>This is the another element.</h2>
  </div>);
}
  
export default App;

 

Output:

React Fragment

It allows us to return the multiple elements from the component, using this we can group the list of children elements.

App.js




import React from 'react';
  
function App() {
  return (<React.Fragment>
    <h1>Hello, There</h1>
    <h2>This is the another element.</h2>
  </React.Fragment>);
}
  
export default App;

Output:

Explanation: Although the output remains the same but the entire key point is while grouping it doesn’t create any extra node. There are a lot of scenarios where this extra div can lead us to a problematic state that’s why we should always prefer fragments for grouping.

Note: We can also use this <> </> syntactic sugar form instead of <React.Fragment> <React.Fragment/>. 




My Personal Notes arrow_drop_up
Recommended Articles
Page :