I am creating chat app and want to auto scroll to bottom automatically in ScrollView
every time a new message received.
Here is my code:
<ScrollView>
<FlatList
data={this.state.dataSource}
renderItem={({ item }) => <SenderChatRow data={item} />}
keyExtractor={(item, index) => index}
/>
{this._bookingRequestMessage()}
</ScrollView>
From React Native 0.41 and later you can use this:
<ScrollView
ref={ref => this.scrollView = ref}
onContentSizeChange={(contentWidth, contentHeight)=>{
this.scrollView.scrollToEnd({animated: true});
}}>
</ScrollView>
Take a look at Docs
As you mentioned you have problem when the keyboard is open, first:
import { Keyboard } from "react-native";
Then use componentDidMount()
:
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow',
this._keyboardDidShow.bind(this));
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow() {
this.scrollView.scrollToEnd({ animated: false })
}
Thanks chetan godiya for the update!
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