I want to slide to the next page by a button event instead of scrolling with a gesture. What I mean by that is, if I were to press the button Next
, I want the page to be scrolled to the following page.
Following is my code with two pages:
export default () => {
const [animation] = useState(new Animated.Value(0))
const onPressHandler = () => {
// this is where I expect the logic should be
}
return (
<SafeAreaView style={styles.container}>
<ScrollView
pagingEnabled
horizontal
scrollEventThrottle={16}
showsHorizontalScrollIndicator={false}
onScroll={Animated.event([
{
nativeEvent: {
contentOffset: {
x: animation,
}
}
}
])}
>
<View style={{ width }}>
<Text>First Page</Text>
<Button title="Next" onPress={onPressHandler} />
</View>
<View style={{ width }}>
</View>
</ScrollView>
</SafeAreaView>
)
}
You can scroll directly using scrollTo
function of ScrollView
Component,It is quite helpful for maintaining index based scroll position.Use it as below.
moveBody = index => {
this.scrollRef.scrollTo({
x: index * width,
animation: false
})
}
<ScrollView pagingEnabled ref={node=>this.scrollRef=node}>
...
</ScrollView
Remember to get correct page make sure the view cover's entire screen width.So that a snap effect can be achieved using next button click.
You can get the index from dividing the offset with the width of the screen.
index=e.nativeEvent.contentOffset.x/width
You can access e
from ScrollView
scroll event like onScroll/onMomentumEnd....
You can also turn off the scroll gesture by assigning false
to scrollEnabled
prop.