• Mail us
  • Book a Meeting
  • Call us
  • Chat with us

ReactJS

React Portals: Render Components Outside the Parent DOM


What Are React Portals?

React Portals provide a way to render a component outside the regular DOM hierarchy while keeping it part of the React tree. This is particularly useful for UI elements that need to break out of their parent containers, like modals, tooltips and dropdowns.

  • Problem: Under normal circumstances, React components are bound within their parent elements, potentially leading to styling or positioning issues.

  • Solution: React Portals allow rendering components directly into the <body> or any other DOM node while maintaining React’s state and event system.

How to Create a React Portal?

React provides the ReactDOM.createPortal() method to create portals.

Basic Example: Creating a Modal Using Portals

 import React from "react";import ReactDOM from "react-dom";const Modal = ({ children, onClose }) => { return ReactDOM.createPortal( <div className="modal-overlay"> <div className="modal-content"> {children} <button onClick={onClose}>Close</button> </div> </div>, document.getElementById("modal-root") // Targeting an external DOM node );};export default Modal;

In your index.html, ensure you have an extra container for modals:

<body> <div id="root"></div> <div id="modal-root"></div> <!-- Separate root for modals --></body>

 

Now, use the Modal component inside another component:

import { useState } from "react";import Modal from "./Modal";const App = () => { const [showModal, setShowModal] = useState(false); return ( <div> <h1>React Portals Example</h1> <button onClick={() => setShowModal(true)}>Open Modal</button> {showModal && <Modal onClose={() => setShowModal(false)}>Hello from the Portal!</Modal>} </div> );};export default App;

Why Use Portals?

Avoids Overflow & Z-Index Issues : Modals won’t be clipped by parent divs.

Maintains Accessibility : Works seamlessly with screen readers.

Does Not Break React Events : Click handlers, state and context still function normally.

Real-World Use Cases for Portals

  • Modals & Dialog Boxes : Prevents interference from parent styles.
  • Tooltips & Popovers : Positions elements outside their container.
  • Dropdown Menus : Ensures menus don’t get hidden inside overflowed containers.
  • Conclusion

    React portals have still provided a powerful way to get out of the ingestion to handle the reaction phenomenon. Whether you are building models, tooltips or dropdowns, ensure better UI behavior and flexibility using portals.

    Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise. 

    0

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    React

    Related Center Of Excellence