Horizontal scrollview snapping react native

Srinivas Guni picture Srinivas Guni · Oct 4, 2016 · Viewed 31.5k times · Source

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 native code to achieve this.

or is there any method to scroll to particular index of scrollview elements like android ?

Any help would be appreciated. Thanks in advance

<ScrollView
  style={[styles.imgContainer,{backgroundColor:colorBg,paddingLeft:20}]}
  automaticallyAdjustInsets={false}
  horizontal={true}
  pagingEnabled={true}
  scrollEnabled={true}
  decelerationRate={0}
  snapToAlignment='center'
  snapToInterval={DEVICE_WIDTH-100}
  scrollEventThrottle={16}
  onScroll={(event) => {
    var contentOffsetX=event.nativeEvent.contentOffset.x;
    var contentOffsetY=event.nativeEvent.contentOffset.y;

    var  cellWidth = (DEVICE_WIDTH-100).toFixed(2);
    var cellHeight=(DEVICE_HEIGHT-200).toFixed(2);

    var  cellIndex = Math.floor(contentOffsetX/ cellWidth);

    // Round to the next cell if the scrolling will stop over halfway to the next cell.
    if ((contentOffsetX- (Math.floor(contentOffsetX / cellWidth) * cellWidth)) > cellWidth) {
      cellIndex++;
    }

    // Adjust stopping point to exact beginning of cell.
    contentOffsetX = cellIndex * cellWidth;
    contentOffsetY= cellIndex * cellHeight;

    event.nativeEvent.contentOffsetX=contentOffsetX;
    event.nativeEvent.contentOffsetY=contentOffsetY;

    // this.setState({contentOffsetX:contentOffsetX,contentOffsetY:contentOffsetY});
    console.log('cellIndex:'+cellIndex);

    console.log("contentOffsetX:"+contentOffsetX);
      // contentOffset={{x:this.state.contentOffsetX,y:0}}
  }}
>
  {rows}

</ScrollView>

Answer

Vasil Enchev picture Vasil Enchev · Aug 3, 2017

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