Giter Site home page Giter Site logo

meliorence / react-native-snap-carousel Goto Github PK

View Code? Open in Web Editor NEW
10.2K 10.2K 2.2K 1.28 MB

Swiper/carousel component for React Native featuring previews, multiple layouts, parallax images, performant handling of huge numbers of items, and more. Compatible with Android & iOS.

License: BSD 3-Clause "New" or "Revised" License

JavaScript 91.04% Java 2.31% Objective-C 3.68% Ruby 2.44% Starlark 0.53%
advanced-effects carousel flatlist-based infinite-scroll parallax-effect swiper

react-native-snap-carousel's People

Contributors

bardiarastin avatar bd-arc avatar bonbonez avatar chitezh avatar creskendoll avatar daaashleywch avatar danielmarkiel avatar exilz avatar florentroques avatar hadishakir avatar ifsnow avatar jakerawr avatar jberivera avatar jonarod avatar martinezguillaume avatar muhlenbrock avatar naffiq avatar naturalclar avatar panpanhan200 avatar r0b0t3d avatar radko93 avatar rgabs avatar sangle7 avatar sergeyzhukov avatar suhanmoon avatar superical avatar thymikee avatar tomauty avatar yamov avatar yjb94 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  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

react-native-snap-carousel's Issues

Observing onScrollToPage event

It will be useful if there is a function prop for observing the scroll events like onScrollToPage / onScrollToItem. e.g.

<Carousel
    ref={'carousel'}
    onScrollToPage={(page) => {
        console.log(page);
    }}
    items={this.state.entries}
    renderItem={this._renderItem}
    sliderWidth={sliderWidth}
    itemWidth={itemWidth}
    slideStyle={styles.slide} />

vertical implementation

Hello,

I'm trying to implement it in vertical, and I want it to know if you have any evolutions on this subject ?

Thanks for this great library !

Adding slides dynamically not rendered at first time

2 -06-2017 23-25-47

By logging out my slides (medicationCards) I am sure that new slide is added to the children of Carousel every time I click ADD.

render() {
    const medicationCards = this.renderMedicationCards(this.props.medications);
    console.log('medicationCards = ', medicationCards);
    return (
      <Carousel
        sliderWidth={SLIDER_WIDTH}
        itemWidth={SLIDE_ITEM_WIDTH}
        slides={medicationCards}
      >
        {medicationCards}
      </Carousel>
    );
  }

However, it is not rendered for the first time.
Based on my loggings, the actual rendered slides fall 1 cycle before slides children updates, e.g. when console.log('medicationCards = ', medicationCards); prints 3 items, 2 are rendered; when it prints 4 items, 3 are rendered.

Android snap is very bad

When you scroll to fast on Android, the snap item is very bad, an is not like in you show case app.

<Carousel
			ref={(carousel) => { this._carousel = carousel; }}
			sliderWidth={sliderWidth}
			itemWidth={itemWidth}
			firstItem={currentIndex}
			inactiveSlideScale={0.9}
			inactiveSlideOpacity={1}
			enableMomentum={false}
			showsHorizontalScrollIndicator={false}
			snapOnAndroid={true}
			enableSnap={true}
			containerCustomStyle={containerCustomStyle}
			contentContainerCustomStyle={contentContainerCustomStyle}
			onSnapToItem={(index) => {
				this.setState({
					currentIndex : index
				});
			}}
			>
                         {this._renderItems()}
                       </Carousel>

any fix about this?

On swipe right on IOS, the view pulls down

Not sure why but only seems to be happening on IOS. Works fine when swiping left but when change direction, the first swipe, will pull down the view revealing the main container. Could this be incompatibility with being nested inside a tab bar view?

after change to ver 2.0.0

when trying to change to the new version all I get is an error on some length as follows:

Cannot read property 'length' of undefined
handleException @ ExceptionsManager.js:63
handleError @ InitializeCore.js:114
reportFatalError @ error-guard.js:44
guard @ MessageQueue.js:48
callFunctionReturnFlushedQueue @ MessageQueue.js:107
(anonymous) @ debuggerWorker.js:71
ExceptionsManager.js:71 Unhandled JS Exception: Cannot read property 'length' of undefined

contentContainerStyle - padding

Hi,

First off, thanks for this package. It's amazing 🖖.

I was wondering something, is there a special reason why
{ paddingHorizontal: containerSideMargin } is added to contentContainerStyle as an own object in an array, instead of doing something like this


 const contentContainerStyle = {
            ....Stylesheet.flatten(contentContainerCustomStyle || {})
            { paddingHorizontal: containerSideMargin }
        }
// if flatten is to costly, one could change the contentContainerCustomStyle prop from a style to an object

The reason I am asking is because I would like to overwrite the paddingHorizontal property
image

Is this something you guys would accept an PR for?

src: https://github.com/archriss/react-native-snap-carousel/blob/master/index.js#L505

Include ListViews as items

Hello,

First of all: nice component, thank you for sharing.

My expected behaviour would be to have items being ListView components.

I copy/pasted you example which works perfectly.
However, If I put a simple ListView instead of the Images for example: nothing renders at all... Not even an error... So I am a bit confused.
This would be what I am trying to achieve:

_renderItem(data, index){
    return (
        <View style={{height: slideHeight}}>
            <View style={{flex:1, backgroundColor:'gray', borderTopLeftRadius:entryBorderRadius, borderTopRightRadius:entryBorderRadius}}>
                <ListView dataSource={this.state.dataSource} renderRow={(rowData) => <Text style={{margin:20, fontSize:30, fontWeight:'bold'}}>{rowData}</Text>}/>  // Nothing renders with this component
            </View>
            <View style={{ justifyContent:'center', paddingVertical:20, paddingHorizontal:16, backgroundColor:'white', borderBottomLeftRadius:entryBorderRadius, borderBottomRightRadius:entryBorderRadius }}>
                <Text style={{ color:'#1a1917', fontSize:13, fontWeight:'bold', letterSpacing: 0.5 }} numberOfLines={2}> { data.toUpperCase() } </Text>
            </View>
        </View>
    );
  }

  render(){
    return (
                    <ScrollView style={{flex:100, paddingTop:10}}>
                      <Carousel
                        items={this.state.numberOfLists}
                        firstItem={0}
                        inactiveSlideScale={1}
                        inactiveSlideOpacity={1}
                        enableMomentum={false}
                        swipeThreshold={sliderWidth/6}
                        renderItem={this._renderItem}
                        sliderWidth={sliderWidth}
                        itemWidth={itemWidth}
                        slideStyle={{flexDirection:'column', width:itemWidth, paddingHorizontal:itemHorizontalMargin}}
                        containerCustomStyle={{marginBottom: 0}}
                        contentContainerCustomStyle={{}}
                        showsHorizontalScrollIndicator={false}
                        snapOnAndroid={true}
                        removeClippedSubviews={false}
                      />
                    </ScrollView>
    )

NOTES:
this.state.numberOfLists = ["1","2","3"]
this.state.dataSource = ds.cloneWithRows(['John', 'Joel', 'James', 'Jimmy', 'Jackson', 'Jillian', 'Julie', 'Devin'])

Would you have any ideas/suggestions on why is this happening??

Merci

Disable stretch height on Carousel Container

Hello,

I am having a problem here, current carousel height is stretched. If i inspect there is a view that having flex:1. I have tried to set containerCustomStyle, contentContainerCustomStyle, slideStyle flex to 0 but the carousel still stretching the height.

<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
  <View>
    <Carousel
      sliderWidth={width}
      itemWidth={width-70}
      showsHorizontalScrollIndicator={false}

      containerCustomStyle={{flex:0}}
      contentContainerCustomStyle={{flex:0,alignItems:'flex-start'}}
      slideStyle={{flex:0}}
      onSnapToItem={this.activeSlide}>

      {items}
    </Carousel>
  </View>
</View>

screenshot_20170412-173449

Choppy behaviour on iOS when slide's width is small

I am having a situation where I want to use the carousel to act like an option picker, the user will swipe to choose a certain option. so I am having a slide width of 80 and the width of the slider is the same as the device width. It's working pretty well on android however it's acting very weird on iOS. it may not be clear here but it's even choppier on an actual device.

Android
mar-26-2017 13-27-52

iOS
mar-26-2017 13-50-20

how to simply make each 'slide' full screen ?

I couldn't easily see how to just set each view on this component 'full screen', so the user can simply swipe left / right. We don't want them to see a preview of the next slide etc. The snippet below is just to try different 'width' setting attempts. flex=1, or screen's width etc. Is this actually possible or does this component require a preview of the next slide etc ?

         <Carousel 
            style={{flex: 1}} 
            sliderWidth={width}     //note: width = Dimensions.get('window') etc..
            itemWidth={width}
            containerCustomStyle={{flex: 1, width: width}}
            contentContainerCustomStyle={{flex: 1, width}}
          >
            <View
               style={{
                  flex: 1, 
                  alignItems: 'center',
                  justifyContent: 'center',
                  backgroundColor: '#B27AF8'
               }}
            >
                  <Text style={{color: '#FFFFFF'}}>I'm the TermsAndPrivacy component</Text>
            </View>
            <View
               style={{
                  flex: 1, 
                  alignItems: 'center',
                  justifyContent: 'center',
                  backgroundColor: 'green'
               }}
            >
                  <Text style={{color: '#FFFFFF'}}>I'm the TermsAndPrivacy component</Text>
            </View>
         </Carousel>

onScroll doesn't get invoked

Env:
"react": "16.0.0-alpha.6",
"react-native": "0.43.3",
"react-native-snap-carousel": "^2.1.2"

Problem:
onScroll does not get invoked whilst scrolling

 <Carousel
    ref={(carousel) => { this._carousel = carousel }}
    sliderWidth={width}
    inactiveSlideScale={1}
    inactiveSlideOpacity={1}
    enableMomentum={false}
    itemWidth={width}
    onSnapToItem={::this._imageIndex}
    onScroll={() => { console.log('onScroll!') }}>
       {imageArray}
  </Carousel>

Make sure that `onSnapToItem` is triggered AFTER scroll animation's completion

Currently, React Native doesn't provide a callback for the scrollTo() method, which is a bummer.

The ScrollView component has a prop onScrollAnimationEnd, but unfortunately this works on iOS only (even though it is referenced in the Java file). Moreover, a bug currently prevents the callback from being fired with horizontal scrollers.

Another lead would be to link the duration of the scroll animation to a timer before firing the callback. Unfortunately, scrollTo() doesn't accept a custom duration.

An idea might be to activate momentum events on Android and see if onMomentumScrollEnd can provide a good enough feedback without impairing performance too much. But this event might not be fired when snapping programatically... Moreover, it is automatically enabled if a momentum callback has been set.

ScrollResponder is another lead worth pursuing...

Does it render all items at once?

Hi,
does this component render all items at once or only visible items are rendered?
does it support removeClippedSubviews prop of ScrollView?

Problem using dynamic data

Hi,

When I use dynamic data I have an error undefined is not an object (evaluating 'this._positions[index].start') but when I use static data everything seem to work.

What I'm doing wrong ?

Thanks.

currentIndex how to work with it ?

I need to get which item is showing or brought to front now . Is it possible through current index? There is no sample provided. Can you help on it ?

Example ?

Hi, the component looks interesting.

Any example to better show how widths should be calculated ?

Cannot swipe the carousel on Android devices

I have run an example using code from your source. It work fine on iOS but totally stuck on Android.
I cannot swipe or move any item like the list is stuck.
Tried on both emulator and real device but it still not working.
Using react v0.44.0
screenshot_20170519-222547

Cannot read property 'style' of undefined

I get this error when I run my tests with jest and it tries to import react-native-snap-carousel :
TypeError: Cannot read property 'style' of undefined at Object.<anonymous> (node_modules/react-native-snap-carousel/index.js:472:842)

firstItem not working

Hey,
I'm having an issue with setting firstItem. Most of the time, the wrong item is selected. We are using a function which returns the children, so we got something like this:

<Carousel
                    ref={'covers'}
                    sliderWidth={viewportWidth}
                    itemWidth={240}
                    inactiveSlideScale={0.9}
                    inactiveSlideOpacity={0.6}
                    showsHorizontalScrollIndicator={false}
                    snapOnAndroid={true}
                    removeClippedSubviews={false}
                    onSnapToItem={this.onSnap}
                    firstItem={8}
                >
                    {this.getCovers()}
</Carousel>

In our case, the 8th item wasn't selected when the component mounts. If we do something like this:

componentDidMount() {
    setTimeout(() => { this.refs.covers.snapToItem(8,false); },500);
}

...the correct item is selected. Are there any issues when generating the childrens via function?

Tapping/Clicking last item causes carousel to snap back to second last item

I have TouchableOpacity child Items within the Carousel component - where the onPress on the TouchableOpacity items work fine.

However, when tapping/clicking on the last item, it will cause the carousel to snap back to the second last item.

Has anyone else experienced the same issue?

// Example
render() {
  const slides = this.props.items.map((entry, index) => {
    return (
      <TouchableOpacity
        onPress={() => { this.props.onPress() }}
        key={`entry-${index}`}
        >
          <View>
            <Image
              style={styles.imageContainer}
              source={entry.illustration}
              />
          </View>
        </TouchableOpacity>
      );
  });

  return(
    <Carousel
      {...this.props}
      ref={(carousel) => { this._carousel = carousel; }}
      showsHorizontalScrollIndicator={false}
      snapOnAndroid={true}
      removeClippedSubviews={false}
      sliderWidth={sliderWidth}
      itemWidth={itemWidth}
      slideStyle = {0}
      onSnapToItem = {(index) => { this.props.onSnapToItem() }}
      >
       { slides }
    </Carousel>
  )
}

Difficulty understand itemWidth / slideWidth props

Would be great to get more clarification around the itemWidth and sliderWidth - especially relating to the examples where calculations are made with inclusions of slideWidth, slideHeight and itemHorizontalMargin

Use onMomentumScrollEnd instead of onScrollEndDrag

Using the option snapOnAndroid currently results in very bad experience where carousel snaps on the item where the drag was released. By using onMomentumScrollEnd instead of onScrollEndDrag here https://github.com/archriss/react-native-snap-carousel/blob/master/index.js#L404 the experience is made much smoother.

Example with onScrollEndDrag: https://gfycat.com/SmallCaringAfricanharrierhawk
Example with onMomentumScrollEnd: https://gfycat.com/PhysicalFearlessBarracuda

Issue with interpolators when upcoming items prop has more elements than current items prop

I've noticed that when there is a change to the items prop, if the length of the upcoming items prop is larger than the current items prop, there will be issues with the interpolators.

Assuming if this.state.myItems currently has 2 items like so:

//default state:
this.state = {myItems: [<View/>, <View/>]};
<Carousel items={this.state.myItems} ... />

No issue when it was initialised at start.
However, when there is change to myItems state at a later time to have more elements, for eg:
this.setState = {myItems: [<View/>, <View/>, <View/>]};

The length of interpolators remained as 2. This will cause an undefined error because the third element in the new myItems cannot access an interpolator for its animation.

For my case, I'm using it with redux and so my state was something like this.props.myItems which came from one of my reducers. But I'm assuming that the same thing will occur with the regular this.state. Also, I'm running it on Android at the moment.

Error when using RN 0.42.3

I've created a barebones react-native [email protected] project and copied the carousel:

<View style={styles.container}>
        <Carousel ref={'carousel'} sliderWidth={200} itemWidth={100}>
          <Text>aaa</Text>
        </Carousel>
      </View>

And getting this error:
screenshot_20170322-141944

_onScroll fails after remove a scrolled item

activeItem in _onScroll is undefined when I remove one item:
In this part after to remove a scrolled item, this.state.interpolators[activeItem] is undefined.

Animated[animationFunc](
              this.state.interpolators[activeItem],
              { ...animationOptions, toValue: 0 }
          ).start();

screen shot 2017-05-07 at 9 31 57 pm

Customise each card of the carousel

This is the BEST ever carousel for React Native I've ever seen or used till date. Looks amazing and a lot promising.

How about exposing a way to customize each card in the carousal. We can have say many layouts predefined and the developer can use the layout that suits his/her requirement.

I can send a PR soon once I get more hands on.

Archriss' showcase app swipe behaviour

Hi,

Can you please share what animationFunc & animationOptions do you use in the Archriss' showcase app? The feeling of the swipe in the example app and in the Archriss' showcase app drastically differ...

Example use of snapToItem()

Dumb question but... How can I programaticaly jump to a given Item respecting animation ?
I see the documentation exposes a snapToItem() method but... do you have some example of using it please?

Apply Cutom Css On "onSnapToItem"

I want to apply custom css "onSnapToItem" for this I am using this.setState({paddingTop: 20}) , I can see this css code when I print "this", but it wont get render, is there anything that I need to do, so that above changes will get reflect on selected item.

How can we handle on press in items?

Thanks for very nice plugin. I am newbie at React Native. I could not handle on press to child item. Is it something that I could figure out or possible issue to be fixed?

   _renderItem (content, index) {
        return (
          <View key={"tours"+index}>
            <TouchableOpacity onPress={this.handlePressSend}>
              <Image source={{uri: 'https://res.cloudinary.com/dhtfjpv7o/image/upload/c_fill,e_art:primavera,g_auto,h_300,w_400/v1479733803/jpfj4ilkpmst3kz697z8.jpg'}} style={styles.tourImage} />
            </TouchableOpacity>
          </View>
        );
    }

On press method;

handlePressSend = () => {
    console.log('pressed')
  }

Implement 'loop' mode

If autoplay is set to true, the carousel jumps from the last slide to the first one whereas it would be better to provide an infinite loop.

Slider shift when item clicked

The slider shift when item is clicked.
2 -06-2017 17-16-05

Here's my code:

const SLIDER_WIDTH = Dimensions.get('window').width;
const SLIDE_ITEM_MARGIN = 35;
const SLIDE_ITEM_WIDTH = SLIDER_WIDTH - (SLIDE_ITEM_MARGIN * 2);
      <Carousel
        sliderWidth={SLIDER_WIDTH}
        itemWidth={SLIDE_ITEM_WIDTH}
        style={{ paddingHorizontal: 0 }}
      >
        {this.renderMedicationCards(this.props.medications)}
      </Carousel>

This does not happen when I set my SLIDE_ITEM_MARGIN to 0, which is setting SLIDE_ITEM_WIDTH = SLIDER_WIDTH = Dimensions.get('window').width

Implement a custom PanResponder

Current momentum implementation doesn't always feel right, particularly on Android. The best way to enhance it and to unify interactions between Android and iOS seems to implement a PanResponder.

Here are some implementations that could serve as a starting point:

Custom interaction ideas:

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.