CreatePortal allows you to render some children in a distinct section of the DOM.
With this, your elements aren’t stuck inside the component tree—you can display them wherever needed!
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;
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;
Ready to transform your business with our technology solutions? Contact us today to Leverage Our Nodejs Expertise.