Reputation: 157
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;
Upvotes: 8
Views: 7544
Reputation: 87
A very clever way to get height of keyboard before it opens, you can store keyboard height on Auth screen and store it to the local storage. That way you'll have keyboard height before it opens in chat screen.
Upvotes: 1
Reputation: 365
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.
Upvotes: 1