Reputation: 31
I have text input and a submit button, I added event on text input of "onendediting", if I put value in textbox and press on submit button without end the editing so the event "onendediting" is not fired as expected. so I want to track the keyboard if keyboard is on I don't allow to submit button to work. How can I handle this ? I used "keyboard.addEventListener" but it wont work.
Upvotes: 3
Views: 4442
Reputation: 3020
NOTE FOR ANDROID: If your Manifest file contains android:windowSoftInputMode="adjustPan"
the hook will not work on Android.
I use a hook for this:
import {useEffect, useState} from 'react';
import {Keyboard} from 'react-native';
const useKeyboard = () => {
const [isKeyboardVisible, setKeyboardVisible] = useState(false);
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
() => {
setKeyboardVisible(true);
},
);
const keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
() => {
setKeyboardVisible(false);
},
);
return () => {
keyboardDidHideListener.remove();
keyboardDidShowListener.remove();
};
}, []);
return isKeyboardVisible;
};
export default useKeyboard;
Usage:
import React from 'react';
import {Text} from 'react-native';
import useKeyboard from './useKeyboard';
const App = () => {
const isKeyboardOpen = useKeyboard();
return isKeyboardOpen ? <Text>OPEN</Text> : <Text>CLOSE</Text>;
};
Upvotes: 3