Update: I've submitted a PR for this to the react-native-community/hooks
repository. https://github.com/react-native-community/hooks/pull/216.
DEMO: Here's a Snack that you can use on your phone to show releasing the keyboard/
One of the very first problems I had to solve while learning React Native was how to dismiss a keyboard when using a standard View
component (vs a ScrollView
).
I wrote about this solution using React classes. Fortunately, now with hooks, the solution is much more elegant and can be easily shared across components. Here's what the hook looks like:
import { Keyboard, Platform } from "react-native";
type Returns = {
shouldSetResponse: () => boolean;
onRelease: () => void;
};
export function useKeyboardRelease(): Returns {
const shouldSetResponse = () => (Platform.OS === 'web' ? false : true);
const onRelease = () => Keyboard.dismiss();
return { shouldSetResponse, onRelease };
}
Feel free to change the name 🤣.
Now, to use the hook in a component, do this:
import { useKeyboardRelease } from "src/hooks/useManageKeyboardRelease";
const { onRelease, shouldSetResponse } = useKeyboardRelease();
<View
onResponderRelease={onRelease}
onStartShouldSetResponder={shouldSetResponse}
>
...
</View>
After that, any clicks on your view will magically close the keyboard ⌨️!