Skip to content

Instantly share code, notes, and snippets.

@swkidd
Created September 23, 2022 05:29
Show Gist options
  • Save swkidd/812a5566a8ddfd0ae7dc6d29537bbd28 to your computer and use it in GitHub Desktop.
Save swkidd/812a5566a8ddfd0ae7dc6d29537bbd28 to your computer and use it in GitHub Desktop.
A React-Native view that shrinks and disappears when the keyboard opens
import React, {useEffect, useRef} from 'react';
import {
Keyboard,
Animated,
} from 'react-native';
function KeyboardShrinkingView({ children, startHeight="100%", endHeight="0%" }) {
const scaleValue = useRef(new Animated.Value(0)).current;
const scaleOut = Animated.timing(scaleValue, {
toValue: 1,
duration: 100,
useNativeDriver: false,
});
const scaleIn = Animated.timing(scaleValue, {
toValue: 0,
duration: 100,
useNativeDriver: false,
});
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
() => {
scaleOut.start();
},
);
const keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
() => {
scaleIn.start();
},
);
return () => {
keyboardDidHideListener.remove();
keyboardDidShowListener.remove();
};
}, []);
return (
<Animated.View
style={{
height: scaleValue.interpolate({
inputRange: [0, 1],
outputRange: [startHeight, endHeight],
}),
opacity: scaleValue.interpolate({
inputRange: [0, 1],
outputRange: [1, 0],
}),
marginVertical: 10,
}}
>
{children}
</Animated.View>
);
}
export default KeyboardShrinkingView;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment