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?
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With