Techy Novice

How to make a keyboard-aware chat view with KeyboardAvoidingView

April 13, 2015

#how-to#react-native

You can directly try out the snack:

You want to build a chat app in React Native and you are now trying to make the chat input goes up with the keyboard. There are so many solutions out there with guides but you haven’t found your sweet spot, something like this:

Demo

TextInput field goes up with the keyboard nicely :)

React Native ships with a component called KeyboardAvoidingView. What it does is simply changing its layout according to the keyboard. This component provides us with 3 different behaviors of changing its layout. For me, using “padding” gives the most predictable outcomes. Basically, when keyboard goes up, this component will add padding to the area that keyboard covers and that moves it’s children up.

content = [1,2,3,4,5,6,7,8,9,10]
<SafeAreaView style={styles.container}>
<KeyboardAvoidingView style={styles.keyboardAvoidContainer} behavior="padding">
<ScrollView style={{flex: 1}}>
{content.map(num => (
<View style={{height: 80, margin: 10, borderWidth: 1, justifyContent: 'center', alignItems: 'center'}} key={num}>
<Text>{num}</Text>
</View>
)}
</ScrollView>
<TextInput style={{height: 40, width: '100%', backgroundColor: '#fff', paddingLeft: 10, justifySelf: 'flex-end', color: '#fff'}} placeholder={'Enter text here'}/>
</KeyboardAvoidingView>
</SafeAreaView>
const styles = {
container: {
flex: 1
},
keyboardAvoidContainer: {
flex: 1,
backgroundColor: 'orange'
}
}

Content will be placed inside a KeyboardAvoidingView in which the elements will be placed to the end of the view (and on top of the keyboard when it goes up)

Using a will yield an effect that can tap outside the keyboard to dismiss it, which is popular in chat apps.

That’s just how simple it is! Enjoy!

Discuss on TwitterEdit on GitHub


Jarvis Luong

Written by Jarvis Luong. I build and share with passion. You can chat with me via Messenger