Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto scroll in ScrollView react-native

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>
like image 330
Yash Vaghela Avatar asked Dec 14 '22 16:12

Yash Vaghela


1 Answers

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

Update

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!

like image 137
MohamadKh75 Avatar answered Dec 22 '22 06:12

MohamadKh75