Skip to content

Instantly share code, notes, and snippets.

@adeleke5140
Created December 7, 2023 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeleke5140/c9a483ab34d5ba813acd426463406e95 to your computer and use it in GitHub Desktop.
Save adeleke5140/c9a483ab34d5ba813acd426463406e95 to your computer and use it in GitHub Desktop.
Custom hook to get and use a container for React portals
const Notifications = () => {
const { container, ref } = useModalParent<HTMLDivElement>();
return (
<div ref={ref}>
// rest of code
<Popover.Portal container={container}>
// rest of code
</Popover/>
</div>
)
}
import { useRef, useState, useEffect } from "react";
//sometimes it can be an HTMLELement or an HTMLDivElement so let's make this generic
export function useModalParent<T extends HTMLElement | HTMLDivElement>(): {
ref: React.RefObject<T>;
container: T;
} {
const [containerInstance, setContainerInstance] = useState<T>();
const ref = useRef<T | null>(null);
useEffect(() => {
if (ref.current) {
setContainerInstance(ref.current);
}
}, []);
//am I sure that the dom element would be present at this point?
let container = containerInstance as T;
return { ref, container };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment