ReactJs Tutorials
React Fragments
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.
File name :
import React from "react";
// Simple rendering with div
class App extends React.Component {
render() {
return (
// Extraneous div element
<div>
<h2>Hello</h2>
<p>How are you sana?</p>
</div>
);
}
}
export default App;
Example
File name : App.js
// Rendering with div tag
class App extends React.Component {
render() {
return (
//Extraneous div element
<div>
<h2> Hello ItTutorial! </h2>
<p> Welcome to the Ittutorial. </p>
</div>
);
}
}
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.
<React.Fragment>
<h2> child1 </h2>
<p> child2 </p>
.. ..... .... ...
</React.Fragment>
Example
File name : App.js
import React from "react";
// Simple rendering with fragment syntax
class App extends React.Component {
render() {
return (
<React.Fragment>
<h2>Hello</h2>
<p>How are you sana?</p>
</React.Fragment>
);
}
}
export default App;
Shorthand Fragment:
we make use of '<>' and '</>' instead of the 'React.Fragment'.
File name : App.js
import React from "react";
// Simple rendering with short syntax
class App extends React.Component {
render() {
return (
<>
<h2>Hello</h2>
<p>How are you sana?</p>
</>
);
}
}
export default App;
Keyed Fragments
Fragments declared with the explicit
function Glossary(props) {
return (
<dl>
{props.items.map(item => (
// Without the `key`, React will fire a key warning
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
);
}
Function = (props) {
return (
<Fragment>
{props.items.data.map(item => (
// Without the 'key', React will give a key warning
<React.Fragment key={item.id}>
<h2>{item.name}</h2>
<p>{item.url}</p>
<p>{item.description}</p>
</React.Fragment>
))}
</Fragment>
)
}
Why we use Fragments?
The main reason to use Fragments tag is:
It makes the execution of code faster as compared to the div tag.
It takes less memory.