# All files / src/Portal Portal.tsx

87.5% Statements 21/24
75% Branches 9/12
80% Functions 4/5
90.91% Lines 20/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    487x
    7x
    7x
    7x

    6x

    6x

    7x

    12x

    12x
    6x

    12x
    6x
    6x
    6x

    12x

    12x

    12x

    7x

    7x

    7x
     import * as React from 'react'
    import * as ReactDOM from 'react-dom'
    import { PortalProps, PortalPropTypes } from './Portal.type'
    import { useGlobal } from '@fluent-ui/hooks'

    function getContainer(container: PortalProps['container']): Element | null {
      container = typeof container === 'function' ? container() : container
      // eslint-disable-next-line
      return ReactDOM.findDOMNode(container) as (Element | null)
    }

    const Portal: React.FC<PortalProps> = React.forwardRef<Element, PortalProps>(
      (
        { children, container, disablePortal = false, ...rest },
        ref
      ): React.ReactPortal | React.ReactElement | null => {
        const [mountNode, setMountNode] = React.useState<PortalProps['container']>(
          (): PortalProps['container'] => container
        )

        React.useEffect((): void => {
          const global = useGlobal() as Window
          Eif (!disablePortal) {
            setMountNode(getContainer(container) || (global && global.document.body))
          }
        }, [container, disablePortal])

        React.useImperativeHandle(ref, (): Element => mountNode as Element, [mountNode])

        Iif (disablePortal) {
          // Verify that children has only one child node (a React element) and return it if it exists,
          // otherwise this method will throw an error.
          React.Children.only(children)
          return React.cloneElement(children)
        }

        return mountNode
          ? ReactDOM.createPortal(React.cloneElement(children, { ...rest }), mountNode as Element)
          : null
      }
    )

    Portal.displayName = 'FPortal'

    Portal.propTypes = PortalPropTypes

    export default Portal