What is react fragment
Fragments basically is a group of a list of children elements without adding extra nodes to the DOM. Let’s see what is an example of react fragment
Ex:
const FragmentDemo = () =>{
return(
<h1>Fragment Demo</h1>
<p>This describes the Fragment Demo Component</p>
)
}
- We created the FragmentDemo() functional component in the above code.
- The component returns a heading using <h1> and we added a simple description using <p> tag.
- But when we do this, we got an error at the line closing parenthesis of the return statement like the below image.
- It says JSX expression must have one parent element, which means any time your component has to return multiple elements you have to enclose them in a single parent element. So, let’s add the enclosing <div> tag.
<div> <h1>Fragment Demo</h1> <p>This describes the Fragment Demo Component</p> </div>
- Now, the <h1> and <p> elements are contained within enclosing <div>. Then save the file and look at the output:
- See the inspect element code, we have enclosed <div> tag included in the DOM tree. So, between the <div> tag from the app component and the <h1> tag in the Fragment Demo component, we have an additional <div> tag. This is well React fragment that comes into the picture.
- We can replace the enclosing <div> tag with React fragment and that will prevent the extra node from being added to the DOM. So, the Fragment Demo component replaces the <div> tag with “React.Fragment” as in the below code.
<React.Fragment> <h1>Fragment Demo</h1> <p>This describes the Fragment Demo Component</p> </React.Fragment>
- Now, see inspect element:
You can see that we no longer have the <div> app component div tag and the <h1> tag.
Shorthand
The shorthand syntax of React fragments is instead of <React.Fragment> we can use empty opening <> and closing tag </>. This basically represents the idea that it won’t add an actual element to the DOM. If you use the shorthand syntax, you can’t pass in the “key” attribute.
<>
<h1>Fragment Demo</h1>
<p>This describes the Fragment Demo Component</p>
</>