Search code examples
react-nativescroll-snap-points

React Native snapToOffsets for only one snap and then scroll normally


Using react native, a ScrollView can snap to respecified points on the y axis of the ScrollView element:

<ScrollView
snapToOffsets={[0,96]}

This will snap to 0 and to 96. It appears however that every subsequent snap point must also be declared.

Is there a way to snap to that point at 96 and then scroll normally without snap offsets from that point going down.

This behaviour can be done on the web with CSS but there is no clear documentation on how to do the same in react. Imagine a header that we want to snap underneath of on the first scroll and then scroll normally thereafter.


Solution

  • Yes there is but it's not perfect. You can get it working as you would expect. The only issue with this solution is that when scrolling up is controlled by Momentum the snap is not triggering.

    With this current limitation in mind, the trick is to use snapToInterval instead and then dynamically update the snapToInterval property onScroll.

    Create a state in the constructor.

    this.state= {
            staticScrollY: 0,
    }
    

    Add a listener to onScroll to track the scroll position.

    listener: (event) => this.handleOnScroll(event.nativeEvent.contentOffset.y)
    

    Create a function between the Constructor and the Render

    handleOnScroll = event => {
            this.setState({
                staticScrollY: event,
            })
        }
    

    User a ternary operator in the snapToInterval property with the amount you want the for the first snap and what the snap should be once greater than that amount.

    snapToInterval={this.state.staticScrollY < 99 ? 98 : 0}
    

    QED..

    PS. added limitation with this solution on Momentum Scroll. If anyone can address that, please post.