CodeBlanks Logo Icon CodeBlanks

What is a portal?

Learn to render a component elsewhere in the DOM with createPortal.

What is a portal?

Normally a component renders into the DOM where it is placed. A portal lets you render a component to a different place in the DOM. It uses ReactDOM.createPortal.

The most common use: modals, dropdowns and notifications. These usually render at the top of the page, independent of all content. Without a portal, a parent's overflow: hidden could clip the modal.

The portal renders elsewhere in the DOM but stays a child of its parent in the React tree; events bubble to the parent.

Modal example

Using a portal for a modal is common. First you define a div id="modal-root" in the HTML; outside the app root, as a direct child of body. The modal component portals into this node.

This way the modal is unaffected by the parent's styles. With position: fixed it covers the screen; z-index puts it on top. Behaviors like click-to-close live in the parent.

When the modal closes, the portal content is removed from the DOM; this provides automatic cleanup.

Practice Modal portal

Complete the skeleton below. Write a ModalPortal component; use createPortal to render <div className="modal">Hello</div> into document.getElementById("modal-root"). Export it.

Starter code

App.jsx
import { createPortal } from "react-dom";

// Write the ModalPortal component here

Sample solution

App.jsx
import { createPortal } from "react-dom";

function ModalPortal() {
  return createPortal(
    <div className="modal">Hello</div>,
    document.getElementById("modal-root")
  );
}

export default ModalPortal;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is a portal most used for?

  • Modal Correct answer
  • Liste
  • Form
  • Tablo

Explanation: It is used for modals, dropdowns and notifications.

2 createPortal call

Question
import { createPortal } from "react-dom";

return createPortal(<Modal />, document.getElementById(____));
Answer
import { createPortal } from "react-dom";

return createPortal(<Modal />, document.getElementById("modal-root"));

Explanation: createPortal(jsx, container) takes the target node as second arg.

3 What is a portal: match the terms

Term Meaning
createPortal Renders into another node
modal-root Target node
modal Common use
overflow: hidden Problem without a portal

All lessons in Intermediate