0
0
ReactHow-ToBeginner · 3 min read

How to Use createPortal in React: Simple Guide with Examples

Use createPortal from ReactDOM to render a React component into a DOM node outside the main app root. It takes two arguments: the React element to render and the target DOM node where it should appear.
📐

Syntax

The createPortal function has this syntax:

  • ReactDOM.createPortal(child, container)

Here, child is the React element you want to render, and container is the DOM node where you want it to appear.

javascript
ReactDOM.createPortal(child, container)
💻

Example

This example shows a modal dialog rendered using createPortal. The modal appears outside the main app root but stays part of React's tree.

javascript
import React, { useState } from 'react';
import ReactDOM from 'react-dom';

function Modal({ children }) {
  const modalRoot = document.getElementById('modal-root');
  return ReactDOM.createPortal(
    <div style={{
      position: 'fixed', top: '50%', left: '50%',
      transform: 'translate(-50%, -50%)',
      background: 'white', padding: '1rem', boxShadow: '0 2px 8px rgba(0,0,0,0.26)'
    }}>
      {children}
    </div>,
    modalRoot
  );
}

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

  return (
    <>
      <button onClick={() => setShowModal(true)}>Open Modal</button>
      {showModal && (
        <Modal>
          <p>This is a modal rendered with createPortal.</p>
          <button onClick={() => setShowModal(false)}>Close</button>
        </Modal>
      )}
    </>
  );
}
Output
A button labeled 'Open Modal'. When clicked, a centered white box appears with text 'This is a modal rendered with createPortal.' and a 'Close' button that hides the modal.
⚠️

Common Pitfalls

  • Not having the target DOM node (container) in your HTML will cause errors or nothing to render.
  • Forgetting to import ReactDOM from 'react-dom' instead of 'react'.
  • Trying to use createPortal inside class components without proper binding or hooks can be tricky.
  • Not managing modal or portal state properly can cause UI glitches.
javascript
/* Wrong: Missing modal-root in HTML */
// ReactDOM.createPortal(<div>Hi</div>, document.getElementById('missing-root'))

/* Right: Ensure modal-root exists in HTML */
// <div id="modal-root"></div> in your index.html

/* Wrong: Importing createPortal incorrectly */
// import { createPortal } from 'react'; // ❌

/* Right: Correct import */
// import ReactDOM from 'react-dom';
// ReactDOM.createPortal(...);
📊

Quick Reference

Tips for using createPortal:

  • Always have the target container element in your HTML.
  • Use portals for modals, tooltips, or overlays that need to escape parent styles.
  • Portals keep React context and event handling intact.
  • Manage portal visibility with React state.

Key Takeaways

Use ReactDOM.createPortal to render components outside the main DOM tree but keep React control.
Pass the React element and a valid DOM node to createPortal.
Portals are perfect for modals, tooltips, and overlays that need to escape CSS overflow or stacking contexts.
Always ensure the target container exists in your HTML to avoid errors.
Manage portal visibility with React state for smooth UI behavior.