Last active
June 13, 2023 09:07
-
-
Save KacperKozak/2bc0e238f035aa99bfcd864d39d21bab to your computer and use it in GitHub Desktop.
Very simple React portal implementation with context
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 { createContext, PropsWithChildren, useContext, useState } from 'react' | |
import { createPortal } from 'react-dom' | |
const PortalContext = createContext<HTMLDivElement | null>(null) | |
export const PortalContextProvider = ({ children }: PropsWithChildren) => { | |
const [element, setElement] = useState<HTMLDivElement | null>(null) | |
return ( | |
<> | |
<div ref={setElement} /> | |
<PortalContext.Provider value={element}>{children}</PortalContext.Provider> | |
</> | |
) | |
} | |
export const usePortalContext = () => { | |
const element = useContext(PortalContext) | |
if (!element) { | |
throw new Error('PortalContext must be used within a PortalContextProvider') | |
} | |
return element | |
} | |
export const Portal = ({ children }: PropsWithChildren) => { | |
const element = usePortalContext() | |
return createPortal(children, element) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment