Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 'Keyboard height before it opens' in React Native?

Environment:

React-Native 0.60.4

Problem:

I'm developing chat app. The chat has emoji picker. Emoji picker must to has the same height that keyboard. I need to get the height of the keyboard before it opens. I tried to use keyboard listeners, but they give height after opening it. My ultimate goal is to do as in the picture. How do you do that?

My ultimate goal

Example:

import React, { useState, useEffect, createRef } from "react";
import {
  Keyboard,
  TextInput,
  View,
  EmitterSubscription,
  Button,
  KeyboardAvoidingView,
  StyleSheet
} from "react-native";

const APPROXIMATE_HEIGHT = 360;

const App = () => {
  let inputRef = createRef<TextInput>();

  const [visible, setVisible] = useState(false);
  const [height, setHeight] = useState(APPROXIMATE_HEIGHT);

  useEffect(() => {
    let keyboardDidShowListener: EmitterSubscription;

    keyboardDidShowListener = Keyboard.addListener(
      "keyboardDidShow",
      keyboardDidShow
    );

    return () => {
      if (keyboardDidShowListener) {
        keyboardDidShowListener.remove();
      }
    };
  });

  const keyboardDidShow = (e: any) => {
    setVisible(false);
    setHeight(e.endCoordinates.height); // sets the height after opening the keyboard
  };

  const openEmojiPicker = () => {
    Keyboard.dismiss();
    setVisible(true);
  };

  const openKeyboard = () => {
    setVisible(false);
    inputRef.current!.focus();
  };

  return (
    <KeyboardAvoidingView style={styles.container} behavior="height" enabled>
      <View style={styles.inputToolBar}>
        <Button
          title={visible ? "Open keyboard" : "Open emoji picker"}
          onPress={visible ? openKeyboard : openEmojiPicker}
        />
        <TextInput placeholder="test" ref={inputRef} />
      </View>
      <View style={[styles.emojiPicker, { height: visible ? height : 0 }]} />
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: "absolute",
    bottom: 0,
    left: 0,
    right: 0
  },
  inputToolBar: {
    flexDirection: "row"
  },
  emojiPicker: {
    backgroundColor: "red"
  }
});

export default App;
like image 513
Андрей Абрамович Avatar asked Aug 11 '19 06:08

Андрей Абрамович


1 Answers

I don't know a very clean way to do this, but you could show the keyboard, get the height, then replace the keyboard with your view.

like image 123
Benjamin Godlove Avatar answered Nov 15 '22 10:11

Benjamin Godlove