React Rendering: Fragments & Portals Explained (w/ Practical Examples)

React Rendering: Fragments & Portals Explained (w/ Practical Examples)

Here’s a detailed explanation of Fragments and React.createPortal with examples:

Fragments:

  • Purpose: To group multiple elements in a React component’s render function without adding extra DOM nodes.

Syntax:

JavaScript

<React.Fragment>
  {/* Elements to group */}
  <h1>Hello</h1>
  <p>World</p>
</React.Fragment>
  • Benefits:
    • Prevent unnecessary divs in the DOM, keeping it clean and efficient.
    • Render multiple elements within conditional statements or loops without extra wrappers.

Example:

JavaScript

function UserCard({ user }) {
  return (
    <React.Fragment>
      <h2>{user.name}</h2>
      {user.email && <p>Email: {user.email}</p>}
    </React.Fragment>
  );
}

React.createPortal:

  • Purpose: To render a component’s output outside of its parent DOM hierarchy, into a different DOM node.

Syntax:

JavaScript

const modalRoot = document.getElementById('modal-root');
const modalContent = React.createPortal(
  <Modal />,
  modalRoot
);
  • Use Cases:
    • Modals and popovers that need to overlay other elements on the page.
    • Integrating React components with third-party DOM elements or frameworks.
    • Handling rendering within iframes or shadow DOMs.

Example:

JavaScript

function Modal() {
  return (
    <div className="modal">
      <p>This is a modal outside the main React tree!</p>
    </div>
  );
}

function App() {
  const [showModal, setShowModal] = useState(false);

  return (
    <div>
      <button onClick={() => setShowModal(true)}>Show Modal</button>
      {showModal && React.createPortal(<Modal />, document.body)}
    </div>
  );
}

Leave a Reply

Your email address will not be published. Required fields are marked *