about summary refs log tree commit diff
path: root/src/lib/hooks/useIsKeyboardVisible.ts
blob: 391090f2d13ddfd12ec622738ace0dd2d6c2947c (plain) (blame)
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
import {isIOS} from 'platform/detection'
import {useEffect, useState} from 'react'
import {Keyboard} from 'react-native'

export function useIsKeyboardVisible({
  iosUseWillEvents,
}: {
  iosUseWillEvents?: boolean
} = {}) {
  const [isKeyboardVisible, setKeyboardVisible] = useState(false)

  // NOTE
  // only iOS supports the "will" events
  // -prf
  const showEvent =
    isIOS && iosUseWillEvents ? 'keyboardWillShow' : 'keyboardDidShow'
  const hideEvent =
    isIOS && iosUseWillEvents ? 'keyboardWillHide' : 'keyboardDidHide'

  useEffect(() => {
    const keyboardShowListener = Keyboard.addListener(showEvent, () =>
      setKeyboardVisible(true),
    )
    const keyboardHideListener = Keyboard.addListener(hideEvent, () =>
      setKeyboardVisible(false),
    )

    return () => {
      keyboardHideListener.remove()
      keyboardShowListener.remove()
    }
  }, [showEvent, hideEvent])

  return [isKeyboardVisible]
}