ReactJS

How to use createPortal in React for flexible component rendering

Why Use createPortal?

CreatePortal allows you to render some children in a distinct section of the DOM.

  • Avoids styling issues – Places the element outside its parent to prevent layout problems.
  • Flexible & reusable – Allows you to move elements anywhere in the document easily.
  • Great for modals, tooltips, and popups – Ensures they appear in the right place without restrictions.

With this, your elements aren’t stuck inside the component tree—you can display them wherever needed!

Create a Common Portal Component

Using React Portals, this component dynamically renders objects beyond the standard React tree.

Children: The JSX elements to render inside the portal.

Id: The ID of an existing DOM element. If not provided, a new <div> is created dynamically.

"use client";
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
const DynamicPortal = ({ children, id }: { children: React.ReactNode; id?: string }) => {
const [container, setContainer] = useState<HTMLElement | null>(null);
useEffect(() => {
let targetElement = id ? document.getElementById(id) : null;
if (!targetElement) {
targetElement = document.createElement('div');
if (id) targetElement.id = id;
document.body.appendChild(targetElement);
}
setContainer(targetElement);
return () => {
if (id && targetElement?.parentNode) {
targetElement.parentNode.removeChild(targetElement);
}
};
}, [id]);
return container ? createPortal(children, container) : null;
};
export default DynamicPortal;

Use the Portal Component in Another Component

DynamicPortal allows you to relocate or portal any DOM element to a different location in the document, anywhere an element with the supplied id exists.

For instance, consider the code below:

import DynamicPortal from './DynamicPortal';
const App = () => {
return (
<div>
<h1>Portal Example</h1>
<DynamicPortal id="custom-portal">
<div className="fixed bottom-5 right-5 bg-blue-600 text-white p-3 rounded shadow">
Portal Content
</div>
</DynamicPortal>
</div>
);
};
export default App;
  • The Portal Content (<div className="fixed bottom-5 right-5 ...">) is moved to the element with id="custom-portal".
  • If an element with that id is present in the DOM, the content gets rendered inside it.
  • If the id is not found, the portal dynamically creates a new container and attaches it to document.body.

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

Contact Us

0

Comment

500

Share

facebook
LinkedIn
Twitter
Mail
ReactJS

Related Center Of Excellence