March 22, 2023

Blog @ Munaf Sheikh

Latest news from tech-feeds around the world.

How do React Fragments work under the hood?


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")
  );
};
Enter fullscreen mode

Exit fullscreen mode



👉 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"
        },
      },
      // ...
    ]
  }
}
Enter fullscreen mode

Exit fullscreen mode

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>
Enter fullscreen mode

Exit fullscreen mode


P.S. Follow me on Twitter for more content like this!





Source link