Created
December 13, 2019 12:11
-
-
Save satya164/3c6b1a11c8b2c8ed8b8d5cbc9683df3c to your computer and use it in GitHub Desktop.
Spacer component to handle keyboard show and hide
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import { Animated, Keyboard, KeyboardEvent, Platform } from 'react-native'; | |
type Props = { | |
offset?: number; | |
}; | |
type State = { | |
keyboardHeightAnim: Animated.Value; | |
}; | |
export default class KeyboardSpacer extends React.Component<Props, State> { | |
static defaultProps = { | |
offset: 0, | |
}; | |
private keyboardHeight = new Animated.Value(0); | |
componentDidMount() { | |
if (Platform.OS === 'ios') { | |
Keyboard.addListener('keyboardWillShow', this.handleKeyboardShow); | |
Keyboard.addListener('keyboardWillHide', this.handleKeyboardHide); | |
} else { | |
Keyboard.addListener('keyboardDidShow', this.handleKeyboardShow); | |
Keyboard.addListener('keyboardDidHide', this.handleKeyboardHide); | |
} | |
} | |
componentWillUnmount() { | |
if (Platform.OS === 'ios') { | |
Keyboard.removeListener('keyboardWillShow', this.handleKeyboardShow); | |
Keyboard.removeListener('keyboardWillHide', this.handleKeyboardHide); | |
} else { | |
Keyboard.removeListener('keyboardDidShow', this.handleKeyboardShow); | |
Keyboard.removeListener('keyboardDidHide', this.handleKeyboardHide); | |
} | |
} | |
private handleKeyboardShow = (e: KeyboardEvent) => { | |
Animated.spring(this.keyboardHeight, { | |
toValue: e.endCoordinates.height - (this.props.offset || 0), | |
}).start(); | |
}; | |
private handleKeyboardHide = () => { | |
Animated.spring(this.keyboardHeight, { | |
toValue: 0, | |
}).start(); | |
}; | |
render() { | |
return <Animated.View style={{ height: this.keyboardHeight }} />; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment