# All files / src/_hooks ZIndex.tsx

100% Statements 28/28
75% Branches 3/4
100% Functions 7/7
100% Lines 19/19

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
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    7870x

    70x

    70x
    8x

    8x

    8x

    8x

    70x
    2x

    2x

    70x
    1x

    70x

    70x
    2x

    70x
    260x

    260x

    260x

     import React from 'react'

    export const defaultZIndex = 9999

    /* TYPES */

    interface ZIndexConfig {
      initialValue?: number
    }

    interface ZIndexApi {
      increment: () => void
      value: number
    }

    interface Props extends ZIndexConfig {
      children?: React.ReactNode
    }

    interface RenderProps extends ZIndexConfig {
      children: (props: ZIndexApi) => {}
    }

    /* HOOK */

    export function useZIndex({
      initialValue = defaultZIndex,
    }: ZIndexConfig): ZIndexApi {
      const [value, setValue] = React.useState(initialValue)

      const increment = () => setValue(value + 1)

      return {
        increment,
        value,
      }
    }

    /* RENDER PROP */

    /**
     * @deprecatedSince 11
     * @deprecated Please use hooks instead
     */
    export function ZIndex({ children, ...props }: RenderProps) {
      const zIndex = useZIndex(props)

      return typeof children === 'function' ? children(zIndex) : children
    }

    /* CONTEXT */

    const noop = (method: string) => () =>
      console.warn(
        `Could not call \`${method}\`, please wrap your component in a \`<ZIndexProvider>\``
      )

    export const ZIndexContext = React.createContext<ZIndexApi>({
      increment: noop('increment'),
      value: defaultZIndex,
    })

    export function ZIndexProvider({ children, ...props }: Props) {
      return (
        <ZIndexContext.Provider value={useZIndex(props)}>
          {children}
        </ZIndexContext.Provider>
      )
    }

    export function useZIndexContext() {
      const ctx = React.useContext(ZIndexContext)

      ctx.value++

      return ctx
    }