Skip to content

Instantly share code, notes, and snippets.

@KacperKozak
Last active June 13, 2023 09:07
Show Gist options
  • Save KacperKozak/2bc0e238f035aa99bfcd864d39d21bab to your computer and use it in GitHub Desktop.
Save KacperKozak/2bc0e238f035aa99bfcd864d39d21bab to your computer and use it in GitHub Desktop.
Very simple React portal implementation with context
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