How to make a keyboard-aware chat view with KeyboardAvoidingView
|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:
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’ | |
} | |
} |
view rawchat-input-keyboard-aware.js hosted with ❤ by GitHub
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!