React Fragments :
Fragment allows you to group a list of childeren without adding extra node.
We can use empty Angular braces <> >
React also provides a "React-Fregment for rendering multiple elements without wrapper.
We can use empty Angular braces <> > .
But in we have react strict mode , if we add that strict mode then empty angular braces won't work.
In React, whenever you want to render something on the screen,
you need to use a render method inside the component.
This render method can return single
elements or multiple elements.
The render method will only render a single root node inside
it at a time.
However, if you want to return multiple elements, the render method will require a
'div' tag and put the entire content or elements inside it.
This extra node to the DOM sometimes
results in
the wrong formatting of your HTML output and also not loved by the many developers.
To solve this problem,
React introduced Fragments from the 16.2 and above version.
Fragments allow you to group a list of children without adding extra nodes to the DOM.
Why we use & Importance of React Fragments :
The execution of code is faster And Also
Less memory is utilised with the use of React fragments as compared to the div tag.
Ex :
class App extends React.Component {
render() {
return (
React.Fragment>
h2 Hello World! h2
p Welcome to the JavaTpoint. p
React.Fragment>
);
Fragments Short Syntax
There is also another shorthand exists for declaring fragments for the above method.
It looks like empty tag in which we can use of '<>' and '' instead of the 'React.Fragment'.
class Columns extends React.Component {
render() {
return (
< >
h2 Hello World! h2
p Welcome to the JavaTpoint p
<>/
);
}
}
Keyed Fragments :