How to detect if user close the keyboard in react native, I want to call a function when user closed the keyboard.
and if you can answer to detect keyboard is open too it will be appreciated, thanks.
I'm on the react native latest version 0.56
To detect when keyboard is opened or closed in React Native, we can call Keyboard. addListener to listen to the 'keybvoardDidShow' and 'keyboardDidHide' events to watch for the keyboard showing and hiding respectively.
Use android:windowSoftInputMode="adjustResize". KeyboardAvoidingView and other keyboard-related components don't work quite well if you have "adjustPan" set for your android:windowSoftInputMode in AndroidManifest. xml . Instead, you should use "adjustResize" and have a wonderful life.
With @react-native-community/hooks you can use the useAppState hook to check the app state. When you close the app, it gets a state of unknown once you open it back. When is in background, it says background' or 'inactive'.
The first thing you have to do is replace the container View with the KeyboardAvoidingView and then add a behavior prop to it. If you look at the documentation you'll see that it accepts 3 different values — height, padding, position. I've found that padding works in the most predictable manner.
Thank you guys for your answers. Here is the hooks version if someone is interested:
const [isKeyboardVisible, setKeyboardVisible] = useState(false); useEffect(() => { const keyboardDidShowListener = Keyboard.addListener( 'keyboardDidShow', () => { setKeyboardVisible(true); // or some other action } ); const keyboardDidHideListener = Keyboard.addListener( 'keyboardDidHide', () => { setKeyboardVisible(false); // or some other action } ); return () => { keyboardDidHideListener.remove(); keyboardDidShowListener.remove(); }; }, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With