Categories
JavaScript Answers React Native Answers

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

Spread the love

Sometimes, we want to detect when keyboard is opened or closed in React Native.

In this article, we’ll look at how to detect when keyboard is opened or closed in React Native.

How to detect when keyboard is opened or closed in 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.

For instance, we write:

import * as React from 'react';
import { ScrollView, View, TextInput, Keyboard, Text } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';
import { Dimensions } from 'react-native';

export default function App() {
  const [keyboardShow, setKeyboardShow] = React.useState();
  React.useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => {
        setKeyboardShow(true);
      }
    );
    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => {
        setKeyboardShow(false);
      }
    );

    return () => {
      keyboardDidHideListener.remove();
      keyboardDidShowListener.remove();
    };
  }, []);

  return (
    <View>
      <TextInput placeholder="input" style={{ marginTop: 100 }} />
      {keyboardShow && <Text>keyboard show</Text>}
    </View>
  );
}

to call Keyboard.addListener to listen to the events.

The callback we pass into addListener runs when the events are emitted.

In the function we return the useEffect callback, we remove the listeners with remove when we unmount the component.

Therefore, we see ‘keyboard show’ when we tap of the input.

Conclusion

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *