Reputation: 459
Im converting a react native project from all class components to functional components with hooks. I have a messaging page with a ScrollView that auto scrolls to the bottom. How do i convert this to work in a functional component? Using ref and this.scrollView cause errors.
<ScrollView
ref={ref => this.scrollView = ref}
onContentSizeChange={(contentWidth, contentHeight)=> {this.scrollView.scrollToEnd({animated: true})}}
>
{...content...}
</ScrollView>
Upvotes: 2
Views: 13091
Reputation: 1425
const scrollRef = useRef(); in function App()
And in onPress use scrollRef.current?.scrollTo({ y: 0, animated: true, });
Upvotes: 1
Reputation: 18929
In the body of your component:
function App(props) {
const scrollViewRef = useRef();
...
On the component:
<ScrollView
ref={scrollViewRef}
onContentSizeChange={(contentWidth, contentHeight)=> {scrollViewRef.current.scrollToEnd({animated: true})}}
>
{...content...}
</ScrollView>
Upvotes: 20