Created
December 7, 2023 23:49
-
-
Save adeleke5140/c9a483ab34d5ba813acd426463406e95 to your computer and use it in GitHub Desktop.
Custom hook to get and use a container for React portals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Notifications = () => { | |
const { container, ref } = useModalParent<HTMLDivElement>(); | |
return ( | |
<div ref={ref}> | |
// rest of code | |
<Popover.Portal container={container}> | |
// rest of code | |
</Popover/> | |
</div> | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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