What is the use of Fragment in React ?
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.
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“.
It allows us to return the multiple elements from the component, using this we can group the list of children elements.
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/>.