React JS - Fragment

Fragment is a pattern to handle multiple elements and multiple components.

Problem Statement :

If we need to write multiple elements inside return() function in a component, then we have to enclose it inside <div> tag as shown below :







The problem using <div> tag is that it takes an extra element in HTML and may create problems sometimes.

Solution :

We can use Fragment. We can use Fragment in 2 ways :

1) Using <React.Fragment>.......</React.Fragment>









2) Using <>.......</> (Shortcut Version)






Github :

https://github.com/eramitsinha/React-Dummy/blob/main/src/Fragment1.js

https://github.com/eramitsinha/React-Dummy/blob/main/src/Fragment2.js

Interview Questions 

  • Can we use className="" in <> (fragment)?

  • Can we use <> (fragment) in Parent Component?

Comments