Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when keyboard is opened or closed in React Native

Tags:

react-native

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

like image 569
RajnishCoder Avatar asked Jul 31 '18 05:07

RajnishCoder


People also ask

How do you check if keyboard is opened react native?

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.

How do I control my keyboard in react native?

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.

How do I know if an app is closed in react native?

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'.

How do you make your react native app respond gracefully when the keyboard pops up?

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.


1 Answers

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();     };   }, []); 
like image 81
5-10 Avatar answered Sep 17 '22 15:09

5-10