Dmitriy Kovalenko
Dmitriy Kovalenko

Reputation: 3636

React native infinity view pager

I need to create infinity view pager to display calendar days, and add an ability to user for swapping left/right and changing date.

As I see in the documentation, the view pager will work only with preset number of views, and also research some opensource packages - cant find anything about that.

So my question - how can I implement infinity swiping for calendar (or is it possible at all)?

Upvotes: 2

Views: 1859

Answers (1)

Richard Lindhout
Richard Lindhout

Reputation: 2068

I have an infinite viewpager made with VirtualizedList. It works on iOS an Android.

import React, { Component } from 'react'
import { View, Text, Dimensions, VirtualizedList } from 'react-native'

const { width, height } = Dimensions.get('window')
const startAtIndex = 5000
const stupidList = new Array(startAtIndex * 2)

class InfiniteViewPager extends Component {
  //only use if you want current page
  _onScrollEnd(e) {
    // const contentOffset = e.nativeEvent.contentOffset
    // const viewSize = e.nativeEvent.layoutMeasurement
    // // Divide the horizontal offset by the width of the view to see which page is visible
    // const pageNum = Math.floor(contentOffset.x / viewSize.width)
  }
  _renderPage(info) {
    const { index } = info

    return (
      <View style={{ width, height }}>
        <Text>
          {' '}{`index:${index}`}{' '}
        </Text>
      </View>
    )
  }
  render() {
    return (
      <VirtualizedList
        horizontal
        pagingEnabled
        initialNumToRender={3}
        getItemCount={data => data.length}
        data={stupidList}
        initialScrollIndex={startAtIndex}
        keyExtractor={(item, index) => index}
        getItemLayout={(data, index) => ({
          length: width,
          offset: width * index,
          index,
        })}
        maxToRenderPerBatch={1}
        windowSize={1}
        getItem={(data, index) => ({ index })}
        renderItem={this._renderPage}
        onMomentumScrollEnd={this._onScrollEnd}
      />
    )
  }
}

Upvotes: 3

Related Questions