I use the ListView's scrollToEnd
, but it doesn't work, but it worked for scrollTo
. What should I do to deal with it.
There is a workaround, wrap it in a setTimeout
like so:
componentDidMount() {
setTimeout(() => {
this.refs.dateList.scrollToEnd();
}, 50);
}
Try this:
<ListView
ref={ ( ref ) => this.scrollView = ref }
onContentSizeChange={ () => {
this.scrollView.scrollToEnd( { animated: false } )
} } >
</ListView>
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
yourArrayData
will cause the useEffect
to call if it changes (if it in state) or has perceived to have changed since React does not run a deep check on objects in a dependency array link, this answer is still a viable solution –
Illustrator 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.
This this worked for me.
<Content ref={c => (this.contentComponent = c)}>
....Any code
</Content >
This allows you to to use the scrollToPosition(0) function like
this.contentComponent._root.scrollToPosition(0);
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>
© 2022 - 2024 — McMap. All rights reserved.
scrollToEnd
method can be used with a button. – Dorsman