Horizontal scrollview snapping react native Horizontal scrollview snapping react native ios ios

Horizontal scrollview snapping react native


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 ithttps://snack.expo.io/H1CnjIeDb


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>    );  }}


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 = 5this.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