Unverified Commit 05b621aa authored by Sukka's avatar Sukka Committed by GitHub

refactor(portal): remove useRef from portal component (#39792)

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`.
parent ea7efcb0
import React from 'react' import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
type PortalProps = { type PortalProps = {
...@@ -6,19 +6,17 @@ type PortalProps = { ...@@ -6,19 +6,17 @@ type PortalProps = {
type: string type: string
} }
export const Portal: React.FC<PortalProps> = ({ children, type }) => { export const Portal = ({ children, type }: PortalProps) => {
let portalNode = React.useRef<HTMLElement | null>(null) const [portalNode, setPortalNode] = useState<HTMLElement | null>(null)
let [, forceUpdate] = React.useState<{}>()
React.useEffect(() => { useEffect(() => {
portalNode.current = document.createElement(type) const element = document.createElement(type)
document.body.appendChild(portalNode.current) document.body.appendChild(element)
forceUpdate({}) setPortalNode(element)
return () => { return () => {
if (portalNode.current) { document.body.removeChild(element)
document.body.removeChild(portalNode.current)
}
} }
}, [type]) }, [type])
return portalNode.current ? createPortal(children, portalNode.current) : null return portalNode ? createPortal(children, portalNode) : null
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment