Skip to content

Instantly share code, notes, and snippets.

@epicbytes
Created May 27, 2023 21:08
Show Gist options
  • Save epicbytes/cd4c3c8cdb05711a9f3e8b04d9250910 to your computer and use it in GitHub Desktop.
Save epicbytes/cd4c3c8cdb05711a9f3e8b04d9250910 to your computer and use it in GitHub Desktop.
Portals in nextJS
export const LayoutPopup = <T extends unknown>({
library,
}: {
library: Record<keyof T, ComponentType<any>>;
}): JSX.Element => {
const modalRoot = useCreateDomElement();
return (
<>
{modalRoot &&
createPortal(<PopupContainer<T> library={library} />, modalRoot)}
</>
);
};
import { useEffect, useState } from "react"
export function useCreateDomElement() {
const [domElement, setDomElement] = useState<HTMLDivElement | null>(null)
useEffect(() => {
const element = document.createElement("div")
document.body.appendChild(element)
setDomElement(element)
return () => {
document.body.removeChild(element)
}
}, [])
return domElement
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment