I use the ListView's scrollToEnd, but it doesn't work, but it worked for scrollTo. What should I do to deal with it.
6 Answers
There is a workaround, wrap it in a setTimeout like so:
componentDidMount() {
setTimeout(() => {
this.refs.dateList.scrollToEnd();
}, 50);
}
4 Comments
Try this:
<ListView
ref={ ( ref ) => this.scrollView = ref }
onContentSizeChange={ () => {
this.scrollView.scrollToEnd( { animated: false } )
} } >
</ListView>
Comments
For functional components, the equivalent is using useEffect like so:
useEffect(()=>{
setTimeout(ref?.current.scrollToEnd());
},[yourArrayData])
Note, you don't need to set a duration for the setTimeout, this is because of Macrotasks in JavaScript, https://javascript.info/event-loop if you want to find out more
2 Comments
Rendering takes time so setTimeout() before scrolling to end will work. You can, however, use the onLayout() method.
export default MyComponent extends React.Component {
constructor(props) {
super(props)
this.scrollToBottom = this.scrollToBottom.bind(this)
}
scrollToBottom() {
this.refs.myView.scrollToEnd()
}
render() {
return {
<ListView
onLayout={this.scrollToBottom}
ref='myView'
...
/>
}
}
Note: ListView is now deprecated.
Comments
I don't think it's good that the top answer is suggesting using a setTimeout, which sort of goes against React's design.
Imo, the best way to handle this (and what worked for me):
- Create and set a ref for the scrollable container
- Have the
onLayout()method on the List element itself trigger the.scrollToBottom()method on the scrollable container ref.
const scrollContainer = useRef();
const scrollToEnd = () => {
chatContainer.current.scrollToEnd();
}
<ScrollView ref={scrollContainer}>
<FlatList onLayout={scrollToEnd}>
</Flatlist>
<ScrollView>


scrollToEndmethod can be used with a button.