React aims to stay neat and clean that’s why fragments are out there. They allow getting rid of excess wrappers while rendering multiple elements!
That’s pretty cool, but how do they work under the hood?
👉 React Fragment is just a React Element of a special type!
JSX is a syntax sugar for calling React.createElement
This function expects only three possible groups of types:
- tag name for basic HTML elements
- class/function for user-defined components
- React fragment type
// what you write
const Items = () => {
return (
<>
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</>
);
}
// what React gets after babel transpilation
const Items = () => {
return React.createElement(
React.Fragment,
null,
React.createElement("li", null, "First element"),
React.createElement("li", null, "Second element"),
React.createElement("li", null, "Third element")
);
};
👉 How does React work with fragments?
After all, there are no corresponding DOM elements!
React doesn’t need real DOM elements to deal with fragments.
It forms a virtual DOM instead 💡
// Items() return this
{
"type": Symbol(react.fragment),
"key": null,
"ref": null,
"props": {
"children": [
{
"type": "li",
"key": null,
"ref": null,
"props": {
"children": "First element"
},
},
// ...
]
}
}
ReactDOM
, in turn, ignores fragments and renders all children without any wrappers.
👉 Verify that it works yourself!
Go to reactjs.org and paste the Items
component.
If DOM looks the same as here 👇, you’ve done a great job!
<div id="___gatsby">
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</div>
P.S. Follow me on Twitter for more content like this!
I’ve just finished my first side-project, thanks to the tips from founders on Twitter!✅ Focused on solving micro-problem
✅ Kept things simple
✅ Resisted the urge of adding more features straight away
✅ Didn’t buy a custom domain first07:42 AM – 12 Feb 2022
More Stories like this
GitHub – droppyjs/droppy: Self-hosted file storage
Jest VSCode Extension | How to code Tutorial.
Import SVGs as React Components | How to code Tutorial