Usage of React Fragments
2 min readDec 30, 2020
Have you ever noticed that in react components every element must wrap inside a parent or else give an error as follows.
import React, { Component } from 'react';class Fragments extends Component {
render() {
return (
<h3>Name</h3>
<p>Please insert the name and tap enter</p>
);
}
}export default Fragments;
And pop up following error.
The reason is you have to wrap those inside a parent or else it will not compile from JSX. To avoid that React Fragments have been introduced. React Fragments can be used as follows.
import React, { Component, Fragment} from 'react';class Fragments extends Component {
render() {
return (
<Fragment>
<h3>Name</h3>
<p>Please insert the name and tap enter</p>
</Fragment>
);
}
}export default Fragments;
In React there is a newer way of Fragmenting which is using just <> and </> which can be implemented as follows.
import React, { Component } from 'react';class Fragments extends Component {
render() {
return (
<>
<h3>Name</h3>
<p>Please insert the name and tap enter</p>
</>
);
}
}export default Fragments;
References
Hopefully this is helpful.
If you have found this helpful please hit that 👏 and share it on social media :).