React Fragment
In React, fragments allow you to return multiple elements in a component without wrapping them in a parent container.
Why use React Fragment?
In React when you render multiple elements it will require a ‘div’ tag around the content as this will only render a single root node inside it at a time.
For example:
import React from 'react' function User() { return ( <p>Hello</p> <p>User</p> ) } export default User; Error!!!
In the above code example, I have tried to render two <p> elements without a parent wrapper. So, this will show an Error!
To correct it you have to add a `<div>` element to wrap those two <p> tags. Like this:
import React from 'react' function User() { return ( <div> <p>Hello</p> <p>User</p> </div> ) } export default User;
In this case if you don’t want to add an extra unnecessary <div> or other container element to the DOM. Then you need to use React Fragment.
For example:
Use this fragment syntax.
import React from 'react' function User() { return ( <React.Fragment> <p>Hello</p> <p>User</p> </React.Fragment> ) } export default User;
Or you can use a shorthand syntax called “empty tags” or “fragment shorthand” (<></>).
import React from 'react' function User() { return ( <> <p>Hello</p> <p>User</p> </> ) } export default User;