05b621aa9c
The PR is similar to #39791. Currently, `<Portal />` saves the container in a ref (with initial value as `null`). The update of the ref happens during the `useEffect`, after creating the corresponding HTMLElement. However, `<Portal />` has to use `forceUpdate` since mutating a ref will not cause the component to update. The PR fixes that by saving the container of the `Portal` in a state, so no more `forceUpdate`.
22 lines
569 B
TypeScript
22 lines
569 B
TypeScript
import { useEffect, useState } from 'react'
|
|
import { createPortal } from 'react-dom'
|
|
|
|
type PortalProps = {
|
|
children: React.ReactNode
|
|
type: string
|
|
}
|
|
|
|
export const Portal = ({ children, type }: PortalProps) => {
|
|
const [portalNode, setPortalNode] = useState<HTMLElement | null>(null)
|
|
|
|
useEffect(() => {
|
|
const element = document.createElement(type)
|
|
document.body.appendChild(element)
|
|
setPortalNode(element)
|
|
return () => {
|
|
document.body.removeChild(element)
|
|
}
|
|
}, [type])
|
|
|
|
return portalNode ? createPortal(children, portalNode) : null
|
|
}
|