Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: improve useKeyboard cross-platform compatibility #401

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 6 additions & 13 deletions src/useKeyboard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {useEffect, useState} from 'react'
import {Keyboard, KeyboardEventListener, KeyboardMetrics} from 'react-native'
import {Keyboard, KeyboardEventListener, KeyboardMetrics, Platform} from 'react-native'

const emptyCoordinates = Object.freeze({
screenX: 0,
Expand All @@ -19,19 +19,14 @@ export function useKeyboard() {
end: KeyboardMetrics
}>(initialValue)
const [keyboardHeight, setKeyboardHeight] = useState<number>(0)
const iosPlatform = Platform.OS === 'ios'

const handleKeyboardWillShow: KeyboardEventListener = (e) => {
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
}
const handleKeyboardDidShow: KeyboardEventListener = (e) => {
const handleKeyboardShow: KeyboardEventListener = (e) => {
setShown(true)
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
setKeyboardHeight(e.endCoordinates.height)
}
const handleKeyboardWillHide: KeyboardEventListener = (e) => {
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
}
const handleKeyboardDidHide: KeyboardEventListener = (e) => {
const handleKeyboardHide: KeyboardEventListener = (e) => {
setShown(false)
if (e) {
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
Expand All @@ -43,10 +38,8 @@ export function useKeyboard() {

useEffect(() => {
const subscriptions = [
Keyboard.addListener('keyboardWillShow', handleKeyboardWillShow),
Keyboard.addListener('keyboardDidShow', handleKeyboardDidShow),
Keyboard.addListener('keyboardWillHide', handleKeyboardWillHide),
Keyboard.addListener('keyboardDidHide', handleKeyboardDidHide),
Keyboard.addListener(iosPlatform ? 'keyboardWillShow' : 'keyboardDidShow', handleKeyboardShow),
Keyboard.addListener(iosPlatform ? 'keyboardWillHide' : 'keyboardDidHide', handleKeyboardHide),
]

return () => {
Expand Down