Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal scrollview snapping react native

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> 
like image 841
Srinivas Guni Avatar asked Oct 04 '16 10:10

Srinivas Guni


1 Answers

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

like image 134
Vasil Enchev Avatar answered Sep 27 '22 20:09

Vasil Enchev