Code for breakfast.

Auto-hiding the Keyboard in React Native

One of the first speed-bumps I hit when starting with React Native was when I tried out my first <TextInput /> - I noticed that tapping outside of the input element didn't hide the virtual keyboard on my device.

After some digging, it turns out RN exposes Keyboard module that gives developers full control of the keyboard.

import { Keyboard } from 'react-native';

Keyboard.dismiss();

Let's make a component that we can use to close the keyboard automatically.

Creating a FormView

import {
  View,
  TouchableWithoutFeedback,
  Keyboard,
} from 'react-native';

export default function FormView({ children }) {
  return (
    <TouchableWithoutFeedback
      onPress={Keyboard.dismiss}
      accessible={false}
    >
      <View style={{ flex: 1 }}>{children}</View>
    </TouchableWithoutFeedback>
  );
}

Alternative: ScrollView

If you're using ScrollView, it provides a prop called keyboardShouldPersistTaps.

Per to the docs - the keyboard will not dismiss automatically when the tap was handled by children of the scroll view (or captured by an ancestor)

import { ScrollView } from 'react-native';

export default function FormView({ children }) {
  return (
    <ScrollView
      contentContainerStyle={{ flexGrow: 1 }}
      keyboardShouldPersistTaps="handled"
    >
      {children}
    </ScrollView>
  );
}