Skip to content

Instantly share code, notes, and snippets.

@tannerlinsley
Last active January 21, 2020 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tannerlinsley/30769bf569a8f96444198bd0eece1fdb to your computer and use it in GitHub Desktop.
Save tannerlinsley/30769bf569a8f96444198bd0eece1fdb to your computer and use it in GitHub Desktop.
A refactor of the old version as requested here in this tweet: https://twitter.com/sseraphini/status/1219701281331257345
import React from 'react'
import PropTypes from 'prop-types'
import { Keyboard, LayoutAnimation, Dimensions, Platform } from 'react-native'
const defaultAnimation = {
duration: 500,
create: {
duration: 300,
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
update: {
type: LayoutAnimation.Types.spring,
springDamping: 200,
},
}
export default function useKeyboardSpacer({
topSpacing = 0,
onChange = () => {},
}) {
const [keyboardSpace, setKeyboardSpace] = React.useState(0)
const onChangeRef = React.useRef()
onChangeRef.current = onChange
React.useEffect(() => {
const updateListener =
Platform.OS === 'android' ? 'keyboardDidShow' : 'keyboardWillShow'
const resetListener =
Platform.OS === 'android' ? 'keyboardDidHide' : 'keyboardWillHide'
const updateKeyboardSpace = event => {
if (!event.endCoordinates) {
return
}
let animationConfig = defaultAnimation
if (Platform.OS === 'ios') {
animationConfig = LayoutAnimation.create(
event.duration,
LayoutAnimation.Types[event.easing],
LayoutAnimation.Properties.opacity
)
}
LayoutAnimation.configureNext(animationConfig)
const newSpace =
Dimensions.get('window').height -
event.endCoordinates.screenY +
topSpacing
setKeyboardSpace(newSpace)
onChangeRef.current(newSpace)
}
const resetKeyboardSpace = event => {
let animationConfig = defaultAnimation
if (Platform.OS === 'ios') {
animationConfig = LayoutAnimation.create(
event.duration,
LayoutAnimation.Types[event.easing],
LayoutAnimation.Properties.opacity
)
}
LayoutAnimation.configureNext(animationConfig)
setKeyboardSpace(0)
onChangeRef.current(0)
}
Keyboard.addListener(updateListener, this.updateKeyboardSpace)
Keyboard.addListener(resetListener, this.resetKeyboardSpace)
return () => {
Keyboard.removeListener(updateListener, updateKeyboardSpace)
Keyboard.removeListener(resetListener, resetKeyboardSpace)
}
}, [topSpacing])
return keyboardSpace
}
useKeyboardSpacer.propTypes = {
topSpacing: PropTypes.number,
onChange: PropTypes.func,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment