Skip to content

Instantly share code, notes, and snippets.

@ashwin1014
Created May 24, 2023 14:43
Show Gist options
  • Save ashwin1014/6bb7d7c1fd0800117547a2aa8bd5f65b to your computer and use it in GitHub Desktop.
Save ashwin1014/6bb7d7c1fd0800117547a2aa8bd5f65b to your computer and use it in GitHub Desktop.
Hook to get keyboard height in react native
import { useEffect, useState } from 'react';
import { Keyboard, KeyboardEvent } from 'react-native';
/**
* Shows height of keyboard when shown
*/
function useKeyboardHeight() {
const [keyboardHeight, setKeyboardHeight] = useState(0);
function onKeyboardShow(event: KeyboardEvent) {
setKeyboardHeight(event.endCoordinates.height);
}
function onKeyboardHide() {
setKeyboardHeight(0);
}
useEffect(() => {
const onShow = Keyboard.addListener('keyboardDidShow', onKeyboardShow);
const onHide = Keyboard.addListener('keyboardDidHide', onKeyboardHide);
return () => {
onShow.remove();
onHide.remove();
};
}, []);
return keyboardHeight;
}
export default useKeyboardHeight;
Copy link

ghost commented Feb 22, 2024

I've noticed that the delay between keyboardDidShow and keyboardWillShow is sometimes severe enough to cause flickering. Refactoring your example, you can watch for either/or and make judgement calls:

import { useEffect, useState } from "react";

import { Keyboard, KeyboardEvent } from "react-native";



/**
 * Shows height of keyboard when shown
 */
export function useKeyboardWillShow() {
  const [ keyboardHeight, setKeyboardHeight ] = useState(0);

  function onKeyboardShow(event: KeyboardEvent) {
    setKeyboardHeight(event.endCoordinates.height);
  }

  function onKeyboardHide() {
    setKeyboardHeight(0);
  }

  useEffect(() => {
    const onShow = Keyboard.addListener("keyboardWillShow", onKeyboardShow);
    const onHide = Keyboard.addListener("keyboardWillHide", onKeyboardHide);

    return () => {
      onShow.remove();
      onHide.remove();
    };
  }, []);

  return keyboardHeight;
}

export function useKeyboardDidShow() {
  const [ keyboardHeight, setKeyboardHeight ] = useState(0);

  function onKeyboardShow(event: KeyboardEvent) {
    setKeyboardHeight(event.endCoordinates.height);
  }

  function onKeyboardHide() {
    setKeyboardHeight(0);
  }

  useEffect(() => {
    const onShow = Keyboard.addListener("keyboardDidShow", onKeyboardShow);
    const onHide = Keyboard.addListener("keyboardDidHide", onKeyboardHide);

    return () => {
      onShow.remove();
      onHide.remove();
    };
  }, []);

  return keyboardHeight;
}

const useKeyboardHeight = useKeyboardDidShow;

export default useKeyboardHeight;

@robinshin
Copy link

^ the keyboardDidShow and keyboardDidHide events are not handled in android facebook/react-native#3468

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment