Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this part we will learn about react fragment and its types, As we know that in ReactJS, render method can display only one element or tag. And if we want to render multiple elements, we were using <div> tag if you remember, but the question is what if we don’t want to use div tag? also, if we create some projects in react then it’s not possible to write whole program into one div tag it will be horrible idea to be honest.
So in that case we have a solution which is ‘fragment’. You can use fragment to write multiple line of code or tags, Let’s have an example to clear this idea:
class App extends React.Component {
render() {
return (
<div>
<h2> Hello World! </h2>
<p> Learn with ReactJS Guru </p>
</div>
);
}
}
This is what we write if we want to render multiple elements, we have used here div. To solve this we have fragment which allows us to group multiple elements without using HTML tags or DOM elements:
class App extends React.Component {
render() {
return (
<React.Fragment>
<h2> Hello World! </h2>
<p> Learn with ReactJS Guru </p>
</React.Fragment>
);
}
}
This is how you can use the React fragment by writing React.Fragment. We also have smaller version if we don’t want to write this whole React.Fragment.
class App extends React.Component {
render() {
return (
<>
<h2> Hello World! </h2>
<p> Learn with ReactJS Guru </p>
</>
);
}
}
As you can see it looks better than upper one, this is small syntax or you can say syntactic sugar form of fragment which is denoted as <>…your code…</>.
The main reason to use fragments tag is:
The shorthand syntax cannot allow keys as attributes. Keys are used for mapping a collection into react fragments, like creating an inventory of descriptions. If you require keys, you need to declare the fragments using explicitly React. Fragment syntax.
Function = (props) {
return (
<>
{props.items.data.map(item => (
<React.Fragment key={item.id}>
<h2>{item.name}</h2>
<p>{item.url}</p>
<p>{item.description}</p>
</React.Fragment>
))}
</>
)
}
You can also prefer this video: