useScrollToTop The expected native behavior of scrollable components is to respond to events from navigation that will scroll to top when tapping on the active tab as you would expect from native tab bars.
In order to achieve it we export useScrollToTop
which accept ref to scrollable component (e,g. ScrollView
or FlatList
).
Example:
import * as React from 'react' ;
import { ScrollView } from 'react-native' ;
import { useScrollToTop } from '@react-navigation/native' ;
function Albums () {
const ref = React . useRef ( null );
useScrollToTop ( ref );
return < ScrollView ref = { ref } > { /* content */ } < /ScrollView>;
}
Using with class component You can wrap your class component in a function component to use the hook:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 class Albums extends React . Component {
render () {
return < ScrollView ref = { this . props . scrollRef } > { /* content */ } < /ScrollView>;
}
}
// Wrap and export
export default function ( props ) {
const ref = React . useRef ( null );
useScrollToTop ( ref );
return < Albums {... props } scrollRef = { ref } /> ;
}
If you require offset to scroll position you can wrap and decorate passed reference:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 import * as React from 'react' ;
import { ScrollView } from 'react-native' ;
import { useScrollToTop } from '@react-navigation/native' ;
function Albums () {
const ref = React . useRef ( null );
useScrollToTop (
React . useRef ({
scrollToTop : () => ref . current ? . scrollTo ({ y : 100 }),
})
);
return < ScrollView ref = { ref } > { /* content */ } < /ScrollView>;
}