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

React Native

React Native Problem Overview


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

React Native Solutions


Solution 1 - React Native

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();
    };
  }, []);

Solution 2 - React Native

1. You can use Keyboard class from facebook.

Here is a sample code.

import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';

class Example extends Component {
  componentWillMount () {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  }
    
  componentWillUnmount () {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }
    
  _keyboardDidShow () {
    alert('Keyboard Shown');
  }
    
  _keyboardDidHide () {
    alert('Keyboard Hidden');
  }
    
  render() {
    return (
      <TextInput
        onSubmitEditing={Keyboard.dismiss}
      />
    );
  }
}

###2. You can use some other npm dependency also, like react-native-keyboard-listener.

Import the component into the file you want to use it:

import KeyboardListener from 'react-native-keyboard-listener';

Use the component directly in your code. The component won't render anything

<View>
  <KeyboardListener
    onWillShow={() => { this.setState({ keyboardOpen: true }); }}
    onWillHide={() => { this.setState({ keyboardOpen: false }); }}
  />
</View>

To install this dependency run below command.

npm install --save react-native-keyboard-listener

Choose any you feel more convenient.

Solution 3 - React Native

Custom Hook:

import { useEffect, useState } from 'react';
import { Keyboard } from 'react-native';

export function useKeyboard() {
  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();
    };
  }, []);

  return isKeyboardVisible;
}

Usage:

import { useKeyboard } from './useKeyboard';
    
const isKeyBoardOpen = useKeyboard();

Solution 4 - React Native

Improved version of @Khemraj 's answer (which worked great for me) with bound methods to the instance in order to be able to update the component's state from the listener and re-render.

import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';

class Example extends Component {

  state = {
      keyboardState: 'closed'
  }

  componentWillMount () {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  }

  componentWillUnmount () {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  _keyboardDidShow = () => {
    this.setState({
        keyboardState: 'opened'
    });
  }

  _keyboardDidHide = () => {
    this.setState({
        keyboardState: 'closed'
    });
  }

  render() {
    return (
      <TextInput
        onSubmitEditing={Keyboard.dismiss}
      />
    );
  }
}

Solution 5 - React Native

I came across the usekeyboard hook found in @react-native-community/hooks

E.g.

import { useKeyboard } from '@react-native-community/hooks'

const keyboard = useKeyboard()

console.log('keyboard isKeyboardShow: ', keyboard.keyboardShown)
console.log('keyboard keyboardHeight: ', keyboard.keyboardHeight)

Source: https://github.com/react-native-community/hooks/blob/master/src/useKeyboard.ts

Solution 6 - React Native

MobX version:

import { observable } from 'mobx'
import { EmitterSubscription, Keyboard } from 'react-native'

class KeyboardStore {
  @observable isKeyboardVisible = false
  keyboardSubs: EmitterSubscription[] = []

  subKeyboard() {
    this.keyboardSubs = [
      Keyboard.addListener('keyboardDidShow', () => this.isKeyboardVisible = true),
      Keyboard.addListener('keyboardDidHide', () => this.isKeyboardVisible = false),
    ]
  }

  unsubKeyboard() {
    this.keyboardSubs.forEach(sub => sub.remove())
    this.keyboardSubs = []
  }
}

and inside top level App component

  useEffect(() => {
    store.subKeyboard()
    return () => {
      store.unsubKeyboard()
    }
  }, [])

and check anywhere in your app with store.isKeyboardVisible.

Solution 7 - React Native

All the thing already avalable in react-native Keyboard class

import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';

class Example extends Component {

    componentDidMount() {
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
        this.keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this._keyboardWillShow);
        this.keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this._keyboardWillHide);
    }

    componentWillUnmount() {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();
        this.keyboardWillShowListener.remove();
        this.keyboardWillHideListener.remove();
    }

    _keyboardWillShow() {
        console.log('Keyboard Showning')
    }

    _keyboardWillHide() {
        console.log('Keyboard Heding')
    }

    _keyboardDidShow() {
        alert('Keyboard Shown');
    }

    _keyboardDidHide() {
        alert('Keyboard Hidden');
    }

    render() {
        return (
            <TextInput
                onSubmitEditing={Keyboard.dismiss}
            />
        );
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajnishCoderView Question on Stackoverflow
Solution 1 - React Native5-10View Answer on Stackoverflow
Solution 2 - React NativeKhemraj SharmaView Answer on Stackoverflow
Solution 3 - React NativeAjmal HasanView Answer on Stackoverflow
Solution 4 - React NativeMoh .SView Answer on Stackoverflow
Solution 5 - React NativeAlex NolascoView Answer on Stackoverflow
Solution 6 - React NativevizView Answer on Stackoverflow
Solution 7 - React NativeAkshay IView Answer on Stackoverflow