How to implement a simple horizontal paginated ScrollView with React Native

Create an horizontal paginated ScrollView with React Native looks simple, but it wasn’t for me because I didn’t know how to size the content correctly. Around the internet a lot of people suggest to use the window size and eventually make some computation on it, but it is not the right solution or, at least, not the easiest.

To create an horizontal paginated ScrollView you need to put inside elements with a fixed width and it has to be equal to the width of the ScrollView. To get the width of the ScollView just use onLayout callback of View.

In the following an example of a SlideShow component.

const imageSize = 200

function SlideShow({ images }) {
  const [width, setWidth] = useState(0)

  return (
    <View style={style.container}>
      <ScrollView
        style={{ width: '100%', height: imageSize }}
        horizontal={true}
        pagingEnabled={true}
        onLayout={(event) => {
          setWidth(event.nativeEvent.layout.width)
        }}
      >
        {Array.isArray(images) && images.map((image, index) =>
          <View
            key={index}
            style={{
              width: width,
              height: imageSize,
              flexDirection: 'row',
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <Image
              source={{ uri: image.url }}
              width={imageSize}
              height={imageSize} />
          </View>
        )}
      </ScrollView>
    </View>
  )
}

Safe and easy:

  • no hard computation of width
  • automatic listening for the correct ScrollView width