By Afaq Shahid Khan
Ever built a modal, toast, or dropdown and hit weird issues with z-index
, overflow: hidden
, or elements being clipped unexpectedly?
Thatβs where React Portals shine! β¨
Letβs break it down in plain English and see how and why you should start using portals today.
π‘ What Is a React Portal?
Normally, React renders components within the parent DOM tree. But sometimes, you want to render something outside of that tree β like a modal that floats on top of everything.
React Portals let you do exactly that: render components outside the main DOM hierarchy, but still keep them fully connected to React (state, events, etc.).
π§ͺ Example:
ReactDOM.createPortal(
<div>I'm outside the main DOM tree!</div>,
document.body
);
Yes β that div
will be rendered as a direct child of <body>
, no matter where the component lives in your React app.
π Build a Toast Notification Using React Portals
Letβs build something practical β a toast popup β and see how portals make it easy.
π¦ 1. Create a Toast Component
import ReactDOM from 'react-dom';
const Toast = ({ message }) => {
return ReactDOM.createPortal(
<div style={{
position: 'fixed',
bottom: '20px',
right: '20px',
backgroundColor: '#333',
color: '#fff',
padding: '12px 24px',
borderRadius: '6px',
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
zIndex: 9999
}}>
{message}
</div>,
document.body // β
No need for a custom portal root!
);
};
export default Toast;
βοΈ 2. Use It in Your App
import { useState } from 'react';
import Toast from './Toast';
function App() {
const [showToast, setShowToast] = useState(false);
const handleClick = () => {
setShowToast(true);
setTimeout(() => setShowToast(false), 3000); // auto-hide after 3s
};
return (
<div>
<button onClick={handleClick}>Show Toast</button>
{showToast && <Toast message="Hello from a portal!" />}
</div>
);
}
export default App;
π― Why Use React Portals?
Common UI Problem | Portals to the Rescue |
---|---|
Modal hidden behind elements | β Portals escape stacking issues |
z-index or overflow: hidden problems |
β Fixed by rendering outside the DOM tree |
Need to float UI anywhere on the page | β Portals let you place UI wherever you want |
β οΈ Tips to Use Portals Effectively
- You donβt need to create a special div like
#portal-root
β just usedocument.body
. - Use portals for things like modals, tooltips, toasts, and dropdowns.
- Donβt overuse them β keep your DOM clean and structured.
π Final Thoughts
React Portals are like teleporters π β they let your components break free from the regular DOM structure, while still staying connected to Reactβs state and event system.
They solve tons of real-world UI problems in a simple way.
If youβre building floating elements or overlays β React Portals are your best friend.
π¬ Have a question or want a working demo with modals or tooltips? Drop a comment below!
β€οΈ If you found this helpful, leave a like and share it with a fellow dev.
π Happy coding!
Top comments (0)