Git Product home page Git Product logo

react-native-viewpager's Introduction

react-native-viewpager

npm version npm downloads

@Deprecated This repo is no more maintenance.

This is the ViewPager componnent in React Native both for Android and iOS. This is a JavaScript-only implementation of pager for React Native. Like ListView, this can render hundreds of pages without performance issue. Better than the one in Android, this ViewPager can auto play -- turn page automaticly, loop -- make infinite scrolling.

Demo

Demo project is here.

Usage

  1. Run npm install react-native-viewpager --save
  2. Code like this:
var ViewPager = require('react-native-viewpager');
<ViewPager
    dataSource={this.state.dataSource}
    renderPage={this._renderPage}/>

More configuration

  • dataSource: this is require to provide pages data,
  • renderPage: this is require to render page view,
  • autoPlay: true to turn page automatically,
  • initialPage: to set the index of the first page to load,
  • isLoop: true to run in infinite scroll mode,
  • locked: true to disable touch scroll,
  • onChangePage: page change callback,
  • renderPageIndicator: render custom ViewPager indicator.
  • initialPage: show initially some other page than first page.

Page Transition Animation Controls

  • animation: function that returns a React Native Animated configuration.

Example:

var ViewPager = require('react-native-viewpager');
<ViewPager
    dataSource={this.state.dataSource}
    renderPage={this._renderPage}
    animation = {(animatedValue, toValue, gestureState) => {
    // Use the horizontal velocity of the swipe gesture
    // to affect the length of the transition so the faster you swipe
    // the faster the pages will transition
    var velocity = Math.abs(gestureState.vx);
    var baseDuration = 300;
    var duration = (velocity > 1) ? 1/velocity * baseDuration : baseDuration;

    return Animated.timing(animatedValue,
    {
      toValue: toValue,
      duration: duration,
      easing: Easing.out(Easing.exp)
    });
  }}
/>

Licensed

MIT License

react-native-viewpager's People

Contributors

christopherabouabdo avatar cornedor avatar developer239 avatar everfire130 avatar fmcorz avatar hufeng avatar jihopark avatar lekenny avatar miguelsm avatar philip-nunoo avatar race604 avatar timzaak avatar tristola avatar yychun1217 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-viewpager's Issues

When looping disabled, block sliding right on first page, and sliding left on last page.

Hello, i don't want to slide beyond the edge when loop is closed. So, again i edited files ViewPage.js file under the node_modules. Here is my code;

// ViewScript.js line: 94
onPanResponderMove: (e, gestureState) => {
  var dx = gestureState.dx;
  var offsetX = -dx / this.state.viewWidth + this.state.childIndex;
  var currentPage = this.state.currentPage;
  var pageCount = this.props.dataSource.getPageCount();

  if(this.props.isLoop || (!(currentPage === 0 && offsetX < 0) && !(currentPage === (pageCount - 1) && offsetX > 1))){
    this.state.scrollValue.setValue(offsetX);
  }
},

Once again i know this is not a good idea. When i will run npm install my changes will be replaced. So I did forked your project and make the changes.

Do you think, it is a good idea?

Wrong (and inconsistent) behavior when rotating the device

Thanks for this plugin.
My app will look ok after rotating to landscape mode, however the pager will be shifted to the right when back to portrait.
I'm not seeing exactly this with your sample app : the top pager is also shifted in landscape but ok when back to portrait, while the bottom page is ok in both modes.

Advanced page transition animation controls

I recently submitted a PR (which was approved) that adds transitionFriction and transitionTension as props that control the friction and tension props of the page transition animation. I realized afterward that I would prefer to have the option to choose between animation types spring vs timing and pass an object containing values for whichever properties each of those animation types accepts.

Like this:

Animated Transition Controls

  • animationType: 'spring' or 'timing'
  • animationProps: object that holds the necessary properties for the animationType provided. Each property should be of the type expected by the corresponding React.Animated method or a function that accepts the gestureState of the swipe that initiated the transition and returns the expected value type.

Example:

var ViewPager = require('react-native-viewpager');
<ViewPager
    dataSource={this.state.dataSource}
    renderPage={this._renderPage}
    animationType="timing"
    animationProps = {{
      duration: (gs) => {
        // Use the horizontal velocity of the swipe gesture
        // to affect the length of the transition so the faster you swipe
        // the faster the pages will transition
        var velocity = Math.abs(gs.vx);
        var baseDuration = 300;
        return (velocity > 1) ? 1/velocity * baseDuration : baseDuration;
      },
      easing: Easing.out(Easing.exp)
    }}
/>

I have implemented this approach in my fork of the repo which I am currently using in my project. I'd love to hear thoughts/ideas on the approach and eventually create another PR if there is interest.

Doesn't work in a ScrollView

No matter what I do, I can't seem to make it work in a ScrollView. It doesn't show up except the dots part.
I have tried all sorts of flex settings, height etc. Please help.

BUG WHEN IMPORT

my react native is the latest version,0.26.1,when i create a new project use
import ViewPager from 'react-native-viewpager';
it report an error
fe011e18-4e55-4035-a9d6-ed3626591372

Event before onChangePage

It would be awesome to fire an event when the transition begins. Something like onChangePageBegin

Override Page indicators doesn't seem to work on 0.17.-rc

I followed exactly what was in the issue #13 , used exactly the same file as DefaultPageIndicators.js you provided, I don't have any errors but the animations doesn't work, the indicators stick to the bottom without moving.

Have you tried to override page indicators on 0.17? I only see this which could be the issue.

Thanks for helping.

How to Override Default Indicator Styles

I want to move dots upper and make them bigger. I can do it by editing, DefaultViewPageIndicator.js file under the node modules but i know it is not right way. Is there better solution for this?

Updated datasource not displayed properly when data array size reduced from 2 to 1

The data will no be displayed or treated as undefined when "splice" the array from length=2 to length=1. The error could cause the app to crash.

Console shows warning message:
Warning: flattenChildren(...): Encountered two children with the same key, .$p_1. Child keys must be unique; when two children share a key, only the first child will be used.

[BUG] the buttons in Image do not work correctly

/**
 * @flow
 */
'use strict';

import React from 'react-native'
import ViewPager from 'react-native-viewpager'
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Dimensions,
  Image,
  TouchableHighlight,
  TouchableNativeFeedback,
  TouchableOpacity,
} = React;
let {width,height} = Dimensions.get('window');

const IMGS = [
  'https://images.unsplash.com/photo-1441742917377-57f78ee0e582?h=1024',
  'https://images.unsplash.com/photo-1441716844725-09cedc13a4e7?h=1024',
  'https://images.unsplash.com/photo-1441448770220-76743f9e6af6?h=1024',
  'https://images.unsplash.com/photo-1441260038675-7329ab4cc264?h=1024',
  'https://images.unsplash.com/photo-1441126270775-739547c8680c?h=1024',
  'https://images.unsplash.com/photo-1440964829947-ca3277bd37f8?h=1024',
  'https://images.unsplash.com/photo-1440847899694-90043f91c7f9?h=1024'
];

export default React.createClass({
  getInitialState: function() {
    var dataSource = new ViewPager.DataSource({
      pageHasChanged: (p1, p2) => p1 !== p2,
    });

    return {
      dataSource: dataSource.cloneWithPages(IMGS),
    };
  },
  _onPressButton:function(id){
    console.log("abc:",id)
  },
  render: function() {
    // return (
    //  <TouchableOpacity onPress={this._onPressButton}>
    //      <Image
   //           source={{uri: 'https://images.unsplash.com/photo-1441448770220-76743f9e6af6?h=1024'}}
   //           style={styles.page} />
    //  </TouchableOpacity>
    // )
    return (
      <ViewPager
        style={{height:300,width:200}}
        dataSource={this.state.dataSource}
        renderPage={this._renderPage}
        isLoop={false}
        autoPlay={false}/>
    );
  },

  _renderPage: function(
    data: string,
    pageID: number | string,) {
    return (
    <TouchableOpacity onPress={()=>this._onPressButton(pageID)}
        background={TouchableNativeFeedback.SelectableBackground()}>
      <Image
        source={{uri: data}}
        style={styles.page} />
    </TouchableOpacity>
    );
  },
});

var styles = StyleSheet.create({
  page: {
    width: width,
    height: 300,
  },
});

pageID is not the correct one!

npm ERR! cb() never called!

node v5.9.0
npm 3.8.3
npm install react-native-viewpager --save
get the error npm ERR! cb() never called!

RenderPage not being called

I have followed the samples provided to implement myself but the render page function isn't being called. The onChangePage function is working correctly but my console.log() is never being triggered inside the render page and as such not displaying anything. Any reason for this @race604? Also to mention I'm not using for my datasource an array of strings but an array of objects (ie. {data: '1', data2: 2'}) but even when I try it with an array of strings it still does not work.

in ViewPager.js render() when pageIDs.length == 1

i use react-native-viewpager-es6
in ViewPager.js render():
when
pageIDs.length == 1
the lines:259/265/273, at the same time to bodyComponents.push
then:
Warning: flattenChildren(...): Encountered two children with the same key, p_0_1. Child keys must be unique; when two children share a key, only the first child will be used.

Warning: flattenChildren(...)

W/ReactNativeJS: Warning: flattenChildren(...): Encountered two children with the same key, .$p_0_1. Child keys must be unique; when two children share a key, only the first child will be used.

Error when tried to use react-native-viewpager

I installed react-native-viewpager using npm.
Then I imported it using var ViewPager = require('react-native-viewpager');
When I tried to place your component ViewPager to render inside render() function, I got error stating "null is not an object (evaluating 'this.state.dataSource')"

Can you provide a snippet to use your component the right way in our projects? Thanks @race604 for such a component!

How to change color and size of page indicators

I saw that there is a file DefaultViewPagerIndicator.js where I can change it but how to use it without modifying your library?

I tried to copy/paste DefaultViewPagerIndicator.js in my project (I called it MyViewPageIndicator) and then:

 renderPageIndicator: function() {
    return(
      <MyViewPageIndicator />
    );
  },

  render: function() {
    global._navigator = this.props.navigator;

    return (
      <ViewPager
        //style={this.props.style}
        dataSource={this.state.dataSource}
        renderPage={this._renderPage}
        //onChangePage={this._onChangePage}
        renderPageIndicator={() => this.renderPageIndicator()}
        isLoop={false}
        autoPlay={false}/>
    );
  },

But it doesn't take effects. Could you provide an example? If I'm going in the right way..

Regards,

Passing initial page to the ViewPager

Is there a way to pass the initial page shown in the viewpager (or currentPage initial value).

<ViewPager initialPage={this.props.initialPage} dataSource={this.ds.cloneWithPages(this.props.pages)} renderPage={this._renderPagefunction} />

The initial value in the ViewPager.js is hardcoded to 0

如何改变ViewPage的高度

我翻看了你的源码,Page页的高度和指示器的高度是可以修改的,但是整体的高度要如何修改呢?

when the page contains by TouchableWithoutFeedback or TouchableQpacity ,it not work well on android

when the page contains by TouchableWithoutFeedback or TouchableQpacity ,it not work well on android.So i have to modify the code like this .

<TouchableWithoutFeedback onPress={()=>{this._onPress(this.state.currentPage)}}>
<View style={{flexDirection:'row'}}>
{bodyComponents}

_onPress(page){
let rowData = this.props.dataSource.getPageData(page);
let callBackData={'rowData':rowData,'pageNo':page};
this.props.onPress(callBackData);

},

Anyone have good ideas please contanct me at [email protected]

How to get Current Page as Variable

Hello,

i am currently working on a new Application in React Native. I used the React Native Viewpager. Everything works fine until now.

Here is my question:

I would like to get the complete amount of 'Pages' and the Index of the currently showing 'Page'. I want to add an Counter such as '5/100', so the User knows where he/she is in the 'List' of Pages.

Any Ideas for an good Solution to generate this counter??

Catch up
Alex

无法在多个页面绑定点击

<ViewPager
            dataSource={this.state.dataSource}
            locked={true}
            ref={viewPager => { this.viewPager = viewPager; }}
            renderPageIndicator={false}
            renderPage={function(data, index){
              if(index == 0) {
                return  (<View style={styles.page}>
                            <Index
                                headerBackgroundImage = {indexView.headerBackgroundImage}
                                listData = {indexView.listData}
                                navData = {indexView.navData}
                              />
                        </View>);
              } else if(index == 1) {
                return (<View style={styles.page}>
                            <Detail />
                          </View>);
              }
            }
          }
          />

在第二个页面绑定点击事件没有效果,触发的却是第一个页面的点击事件,如何处理

ViewPageIndicator childIndex issues

When going to a page with initialPage and loop the dot is at the correct place, but when rendering index 0, it point at dot 1. I had to fix manually with scrollOffset: this.childIndex || 1, which I'm not very proud of.

Anybody experienced this ?

When isLoop set to true - Pager begins in the incorrect state

Hi, This is a really nice component and I'm trying to use it in a couple of places in my app in loop mode. The problem I'm facing is that when the ViewPager loads, the indicators show that it is on the second image, but the first image is showing. Then when I attempt to scroll, it jumps to the second image and the first image scrolls in. Once the first scroll is complete, the second image reappears over the first.

It appears to be doing this in the sample app. Am I doing something wrong?

Invalid prop `renderPageIndicator` of type `boolean`

If I set renderPageIndicator to false, as in:

<ViewPager
  renderPageIndicator={false}
  ( ... rest of attributes ... ) />

I get the following message:

Warning: Failed propType: Invalid prop renderPageIndicator of type boolean supplied to ViewPager, expected function.

Even though false appears to be a valid value:

// from ViewPager.js, line 178
if (this.props.renderPageIndicator === false) {
  return null;
}

 get two BUG

1 pictures more than 5 Loop of the first will be refresh
2 the default focus is second

Not working on Android

I have read that this component works on both platforms, Android and iOS\

"This is the ViewPager componnent in React Native both for Android and iOS."

But, I've integrated react-native-viewpager in my app, its working fine on iPhone but breaks on Android devices. I'm unable to swipe through the pages on my android device.

Do anyone have working example of this component?

P.S: It breaks even if I tried to run simple Demo example of images mentioned in its Docs. I'm using react-native v0.20.

bad performance

Hi,
I'm trying to build dynamic viewer - that can have pages added or removed.
I've set

var dataSource = new ViewPager.DataSource ({
    pageHasChanged: ( p1, p2 ) => p1 !== p2
});

as a global var, and added

setState({dataSource: dataSource.cloneWithPages(this.state.pages)})

to initialState and to add/removePage methods.

while it is working - the performance of scrolling and adding pages is quite slow (fps around 30), making it a non-option.

I'm not sure what i'm doing wrong, sunce my renderPage method is quite standard, and works fine (and smooth) with the native Components (ScrollView and ViewPagerAndroid).

ViewPager.js: Unable to resolve module StaticRenderer

Hello, thank you for this useful component. I have a problem since upgrading to RN-v0.14.0-rc (I'm not sure it's related) :
Error while loading: Unable to resolve module StaticRenderer from /Users/yosemit/Documents/Chat_Test/node_modules/react-native-viewpager/ViewPager.js: Invalid directory /Users/node_modules/StaticRenderer

Any idea what is the cause of this error? Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.