Search code examples
javascriptreactjsreact-nativescrollview

React Native Scroll View to keep track of full page scroll location


I have a scroll view that contains an image that covers the entire screen. There are two buttons at the bottom of the screen, these will allow you to download or set the image as a wallpaper. The problem I'm having is I don't know which image is being looked at in the horizontal scroll view when the button is clicked.

I have knowledge of the screen size and was assuming if I could get the content offset or something like that from the currently viewed image in the view divided by the screen size could let me know what image in the array I'm looking at to perform the rest of the functionality.

Unfortunately, I'm unaware of how this could be done the code is below to give a bit of context.

        <ScrollView 
          horizontal
          decelerationRate={0}
          snapToInterval={width}
          snapToAlignment={"center"}
          style={{ height: height }}
        >
          {
            availibleBackgrounds.map(element => (
              <Image
                style={{ width: width, height: height, justifyContent: 'flex-end', alignItems: 'center' }}
                source={{
                  uri: element
                }}
              />
            ))
          }
        </ScrollView>

Solution

  • You need to get the offset of the content and you can do it with adding the following prop the the ScrollView:

    onMomentumScrollEnd={event => setSelectedIndex(event.nativeEvent.contentOffset.x/width)}
    

    setSelectedIndex is a function you should create.