mirror of
https://github.com/zhigang1992/react.git
synced 2026-03-01 09:15:00 +08:00
37 lines
975 B
TypeScript
37 lines
975 B
TypeScript
import { useEffect, useState } from 'react'
|
|
import useSSR from '../utils/use-ssr'
|
|
import { getId } from './collections'
|
|
|
|
const createElement = (id: string): HTMLElement => {
|
|
const el = document.createElement('div')
|
|
el.setAttribute('id', id)
|
|
return el
|
|
}
|
|
|
|
const usePortal = (
|
|
selectId: string = getId(),
|
|
getContainer?: () => HTMLElement | null,
|
|
): HTMLElement | null => {
|
|
const id = `geist-ui-${selectId}`
|
|
const { isBrowser } = useSSR()
|
|
const [elSnapshot, setElSnapshot] = useState<HTMLElement | null>(
|
|
isBrowser ? createElement(id) : null,
|
|
)
|
|
|
|
useEffect(() => {
|
|
const customContainer = getContainer ? getContainer() : null
|
|
const parentElement = customContainer || document.body
|
|
const hasElement = parentElement.querySelector<HTMLElement>(`#${id}`)
|
|
const el = hasElement || createElement(id)
|
|
|
|
if (!hasElement) {
|
|
parentElement.appendChild(el)
|
|
}
|
|
setElSnapshot(el)
|
|
}, [])
|
|
|
|
return elSnapshot
|
|
}
|
|
|
|
export default usePortal
|