Skip to content
GSGurmeet Singh
All posts

2 min read

What is createPortal()?

Recently, I ran into a tricky UI issue in React… but then I found createPortal() and it saved the day! 🚀

I was working on a modal that needed to overlay everything—including elements with overflow: hidden or z-index constraints. But no matter what I tried, my modal was getting trapped inside its parent container. 😩

Then I discovered ReactDOM.createPortal(), and wow—this was exactly what I needed! It lets you render a component outside its normal React hierarchy, meaning I could place my modal directly inside document.body and avoid all those layout issues.

What is createPortal()?

Normally, React components render inside their parent DOM tree. But createPortal() lets you render a component somewhere else in the DOM while keeping its React state and event handling intact.

Here’s a simple example:

import React from "react";

tsx
import ReactDOM from "react-dom";
const Modal = ({ children }) => {
return ReactDOM.createPortal(
<div className="modal">{children}</div>,
document.getElementById("modal-root") // This is outside the main app root
);
};
const App = () => {
const [show, setShow] = React.useState(false);
return (
<div>
<button onClick={() => setShow(true)}>Open Modal</button>
{show && (
<Modal>
<div className="modal-content">
<p>This modal is rendered outside the normal DOM hierarchy!</p>
<button onClick={() => setShow(false)}>Close</button>
</div>
</Modal>
)}
</div>
);

};

Why use createPortal()?

✅ Avoids overflow: hidden and z-index issues
✅ Keeps event propagation intact
✅ Useful for modals, tooltips, popups, and dropdowns

If you’ve ever struggled with UI elements getting trapped inside containers—give createPortal() a try! It’s a game-changer. 💡

Have you used createPortal() before? What’s your experience with it? Let’s discuss in the comments! ⬇️

4 min read

How React Works Behind the Scenes

React is one of the most popular libraries for building user interfaces, but have you ever wondered how it actually works under the hood? This article unpacks React’s internal…