Hi I am trying to achieve scrollview
snap to center
like below gif
link
Check This Gif
But unable to do so. Following is my react nat
Use the pagingEnabled
property in ScrollView
.
const screenHeight = Dimensions.get('window').height;
class Screen extends Component {
constructor(props) {
super(props);
}
render() {
return (
<ScrollView pagingEnabled>
<Page1 style={{height: screenHeight}} />
<Page2 style={{height: screenHeight}} />
</ScrollView>
);
}
}
You don't need other libraries you can do that with ScrollView. All you need is to add the following props in your component.
horizontal= {true}
decelerationRate={0}
snapToInterval={200} //your element width
snapToAlignment={"center"}
Check this snack for more details on how to implement it https://snack.expo.io/H1CnjIeDb
There are several options. Here are two that I've tried and work fine. I prefer the second one because as its doc says "like ListView, this can render hundreds of pages without performance issue".
If you don't want to use snapToInterval because of the misalignment for long lists you can use snapToOffsets which is more precise.
for example:
const { width } = Dimensions.get('window');
this.IMAGE_WIDTH = width * (1 / 2.5)
this.image_margin = 5
this.nishhar = width - ((this.IMAGE_WIDTH + this.image_margin) * 2 + this.image_margin * 2)
dataNum = [1, 2, 3, 4, 5, 6]
return (<FlatList
data={dataNum}
renderItem={item => {
return (
<View style={{
backgroundColor: item.index % 2 == 0 ? 'red' : 'blue',
width: this.IMAGE_WIDTH,
height: this.IMAGE_WIDTH,
marginLeft: this.image_margin,
marginRight: this.image_margin,
}}>
</View>)
}}
keyExtractor={this.keyGenerator}
horizontal={true}
snapToAlignment={"start"}
snapToOffsets={[...Array(dataNum.length)].map((x, i) => (i * (this.IMAGE_WIDTH + 2 * this.image_margin) - (this.nishhar * 0.5)))}
decelerationRate={"fast"}
pagingEnabled
/>)
or you can also checkout this example: https://snack.expo.io/SyWXFqDAB