Coder Social home page Coder Social logo

namlehoangdev / react-native-anchor-carousel Goto Github PK

View Code? Open in Web Editor NEW
125.0 3.0 30.0 8.29 MB

A simple swipeable carousel for React Native which anchor two side of list.

Home Page: https://www.npmjs.com/package/react-native-anchor-carousel

License: MIT License

JavaScript 62.01% Java 17.65% Objective-C 12.78% Starlark 5.45% Ruby 2.11%
carousel swiper swipable paging flatlist scrollview anchor

react-native-anchor-carousel's Introduction

react-native-anchor-carousel


Build Status

A simple swipeable carousel for React Native which anchor two side of list.

Installation

Install the dependency.

$ npm install react-native-anchor-carousel 
$ yarn add react-native-anchor-carousel 


For older version, install 3.1.2

$ npm install [email protected]
$ yarn add [email protected] 

Example

Expo snack demo here


full example here

import Carousel from 'react-native-anchor-carousel';
const {width: windowWidth} = Dimensions.get('window');
const styles = StyleSheet.create({
 carousel: {
  flexGrow: 0,
  height: 150,
 }
});


Hook Component version:

const carouselRef = React.useRef(null);
renderItem = ({item, index}) => {
 return (
         <TouchableOpacity
                 style={styles.item}
                 onPress={() => {
                  carouselRef.current.scrollToIndex(index);
                 }}>
          ...
         </TouchableOpacity>
 );
}
return (<Carousel
        ref={carouselRef}
        data={Array(3).fill(0)}
        renderItem={renderItem}
        style={styles.carousel}
        itemWidth={windowWidth * 0.8}
        containerWidth={windowWidth}
        separatorWidth={0}
/>)


Traditional Class Component version:

renderItem = ({item, index}) => {
 return (
         <TouchableOpacity
                 style={styles.item}
                 onPress={() => {
                  this.numberCarousel.scrollToIndex(index);
                 }}>
          ...
         </TouchableOpacity>
 );
};

render() {
 return (
         <Carousel
                 style={styles.carousel}
                 ref={c => {
                  this.numberCarousel = c;
                 }}
                 data={Array(3).fill(0)}
                 renderItem={this.renderItem}
                 itemWidth={windowWidth * 0.8}
                 separatorWidth={0}
                 containerWidth={windowWidth}
         />
 );
}

Usages

This component currently just support only carousel for horizontal side carousel From version 2.2.0.
It is now supported Flatlist props from version 3.0.0 Change scroll behavior of previous versions
From version 4.0.0 it has been moved to Functional component and fix separator bug

Props Description Type Default Required
data Array of data for rendering Array [] Yes
renderItems take each item from data and renders it. Function receives one agrument {item,index} and must return as React.Element Function () => {} Yes
keyExtractor Key extractor for each item of list Function (item, index) => index.toString() Should
Other Flatlist Props Other Flatlist Props
minScrollDistance Minimum distance when scrolling to move to the next item. Notice this property when you need to improve smoothness Number 5 No
containerWidth Width of the carousel container box Number Screen width Yes
itemWidth Width of each item in carousel Number 90% of screen width Yes
separatorWidth Width of separator in carousel (cause it only support horizontal side at the present time) Number 10 No
inActiveScale Value of the scale effect applied to inactive item Number 0.8 No
inActiveOpacity Value of the opacity effect applied to inactive item Number 0.8 No
style Style of the carousel container box View style {} No
itemContainerStyle Style for each carousel container item View style {} No
onScrollEnd Fired while scrollview end of scrolling Function ()=> {} No
initialIndex Initial starting focused item of list Number 0 No

References from

This library is written after taking reference from react-native-snap-carousel

Development

Welcome everybody to contribute ! Hope this simple carousel can help somebody for fast develope react-native app!

Todos

  • Cover vertical side carousel

License

MIT

Free Software, Hell Yeah!

react-native-anchor-carousel's People

Contributors

namlehoangdev 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

react-native-anchor-carousel's Issues

is there way to reposition last item ?

so in my case is, i want the first and last item to be anchor not on the edge of screen, but want to scroll them off to the edge of screen, sorry but it quite hard to explain, so i will make bullet point for it

  • "but want to scroll them off to the edge of screen" - this works wondefully of course, theres no complain

  • " i want the first and last item to be anchor not on the edge of screen" - now this one is cause bit of a problem, basically i want to pad the first item about 10px from left edge of screen, and the last item 10px from edge of right part of the screen, now, for the first item, it works just by putting paddingHorizontal on style, but it doesnt influence the last item

is there way to do this ?

Need help with current index of carousel

The only thing that I didn’t succeed is to set a variable of my state with the current selected index of the carousel. Can someone help me out with that? It looks like the carousel already know this index because is able to set inactive scale and opacity for the rest of the items. But I need that in my component. Part of my code is:
`export const carouselItems = [
{ text: 'NIR', value: 0 },
{ text: 'Both', value: 2 },
{ text: 'Red', value: 1 }
];

setOptionIndex = index => {
this.setState({ optionIndex: index });
this._carousel.scrollToIndex(index);
};

_renderItem = ({ item, index }) => {
const { optionIndex } = this.state;
return (
<TouchableOpacity onPress={() => this.setOptionIndex(index)}>
<Text style={optionIndex === index ? styles.selectedOption : styles.selectedOption}>{item.text}

);
};

<Carousel
style={styles.carousel}
data={carouselItems}
renderItem={this._renderItem}
containerWidth={sliderWidth}
itemWidth={100}
inActiveScale={0.7}
inActiveOpacity={0.4}
pagingEnable={true}
ref={(c) => {
this._carousel = c;
}}
minScrollDistance={30}
initialIndex={1}
/>
`

image
Attached is a small screenshot from my app. I want to know in this screen on what index is the carousel.

Pagination Dots

Would be great if this library had a pagination control with dots, or number according to the number of slides available.

GYoJW

Scrolling "jank" in android with expo 43 and recent RN versions.

Describe the bug
When a user swipes left or right QUICKLY on an android, there is an undesirable (and janky looking) "stutter" effect. Hard to describe with words because it happens so quickly, but suffice it to say the animation is not smooth and leads to a broken looking experience.

To Reproduce
Steps to reproduce the behavior:
Animation is fine with expo 42 and below (and, presumably, older versions of react). Jank is observable in expo 43 and recent versions of react-native (I'm using 0.66.4).

  1. Load the official expo demo url on your android device
  2. Opt in to Expo 43 image
  3. Swipe left or right quickly -- easiest to observe on the "ShopCarousel" and "ImageCarousel".

Expected behavior
A smooth animation/transition is expected.

Smartphone:
Samsung Note 20

  • OS: Android
  • Version: 12

Samsung S9+

  • OS: Android
  • Version: 10

Supporting RTL?

Does all images only slides from Left to Right (Arabic Language). I have Arabic Languages images (RTL) which needs swiping from RTL. How can I do that?

Calling `getNode()` on the ref of an Animated component is no longer necessary

Using react-native-anchor-carousel gives me the warning below

FlatList: Calling getNode() on the ref of an Animated component is no longer necessary. You can directly use the ref instead. The method will be removed in future release

Packages:

  • react: 16.11.0
  • react-native: 0.62.2
  • react-native-anchor-carousel: 3.1.2

Smartphone:

  • Device: Redmi Note 8 Pro
  • OS: Android 10

Calling `getNode()`

I keep getting this error %s: Calling getNode() on the ref of an Animated component is no longer necessary. You can now directly use the ref instead. This method will be removed in a future release., FlatList at node_modules\expo\build\logs\LogSerialization.js:155:14 in _captureConsoleStackTrace at node_modules\expo\build\logs\LogSerialization.js:41:26 in serializeLogDataAsync anytime i try to swipe to next carousel

ScrollToIndex causing swiping issues only for first time

Describe the bug
When there are multiple cards on the carousel if the second carousel card is highlighted when swiping right, instead of moving left and displaying the first card it is moving right and displaying the third card. It also happens only for the first time.

To Reproduce
Steps to reproduce the behavior:

  1. Have multiple cards for example 5 cards (1, 2, 3, 4, 5)
  2. By default display the 2nd card highlighted
  3. Swipe left to display the 1st card
  4. It is swiping to right and displaying the 3rd card

Expected behavior
It should swipe left and display the 1st card

Smartphone (please complete the following information):

  • iPhones
  • iOS 15.0

Additional context
Add any other context about the problem here.

Only the first image is loaded when used in Flatlist

Describe the bug
A clear and concise description of what the bug is.

When I used it in a Flatlist, only the first image is loaded. The user has to wait for lazy loading the rest of the images in the carousel.

To Reproduce
Steps to reproduce the behavior:
Just use it in a Flatlist.

Expected behavior
A clear and concise description of what you expected to happen.
Images should all be loaded along with the first image in a Flatlist

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS] Windows 11
  • Browser [e.g. chrome, safari] Chrome
  • Version [e.g. 22] Windows 11

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6] Huawei Mate 10 Pro
  • OS: [e.g. iOS8.1] Android 10
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Error: scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed

Describe the bug
I've implemented this library to show item cards in a container which is modal view. I think it's due to prop bcoz when I remove this prop then it's showing me my view with all cards.

initialIndex

But I need to show my first item card which would be selected by user from list view and which has index "this.props.currentSelectedIndex"

<Carousel style = {styles.carouselContainer} data = {this.state.entries} initialIndex = {this.props.currentSelectedIndex} renderItem = {({item, index}) => this.renderItem({item, index})} itemWidth = {globalFunction.wp(70) + (globalFunction.wp(5) * 4)} containerWidth = {Constants.iDeviceWidth} inActiveScale = {0.95} separatorWidth = {10} ref = {(c) => { this._carousel = c; }} itemContainerStyle = {styles.slideContentContainer} />

and my renderItem function is like below

renderItem ({item, index}) { let jsonData = JSON.parse(item.jsonRepresentation); let activeIngredientDetails = jsonData; let ingredientDetailsDynamicTabsArray = globalFunction.getDynamicTabsForIngredient(activeIngredientDetails, this.props.userData.accesses); return <IngredientCard allIngredientsData = {this.state.entries} data = {item} ingredientIndex = {index} tabsArray = {ingredientDetailsDynamicTabsArray} userDetails = {this.props.userData} />; }

IngredientCard is a pure component within same class only.

But I'm getting an error - scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed, otherwise there is no way to know the location of offscreen indices or handle failures.

and my Xcode console logs - Unhandled JS Exception: scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed, otherwise there is no way to know the location of offscreen indices or handle failures.

Screenshots

Simulator Screen Shot - iPhone X - 2019-08-29 at 20 13 41

Desktop (please complete the following information):

  • OS: [e.g. iOS 12.4]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone8]
  • OS: [e.g. iOS12.3]

Additional context
my react-native environment from package.json

"react": "16.8.3",
"react-native": "^0.59.9",
"react-native-anchor-carousel": "^3.1.0",

Please tell me how to resolve this error.

And, If you have any logic for displaying large data say 2000 in batches then please share it as well.

Thanks in advance.

TypeScript support

Is your feature request related to a problem? Please describe.
I'm having issues using this in a typescript project

Describe the solution you'd like
Types declaration

Describe alternatives you've considered
I've declared a module in declarations.d.ts but trying to use this with useRef in typescript is not easy

Additional context
Add any other context or screenshots about the feature request here.

scrollToIndex not working correctly

I have a large list of local images. when reaching 10 images I load 10 new ones. and I scrollToIndex(0).
at first it works perfectly, but at the last list (<10 images) it doesn't scrollToIndex(0) but it still at the last one.


onPress={() => { this.loadmore(index); }}


loadmore= (ind) =>{

var nxt=ind+1

if(nxt<10 ){this._carousel.scrollToIndex(nxt);
  console.log("ind=",ind+1);

}

else{

console.log("EndReached ind=", nxt);
console.log("last_page",this.state.last_page);
    
    var j=this.state.last_page +10;

    this.setState({
      last_page:j      
    });
    
    if(j<long){
    this.setState({ animating: true})
    
    var temp = [];
    
    for (let i = j; i < long && i<j+10 ; ++i) {
      temp.push(Slidesdata[bab_id].images[i]);
      console.log('i=',i);
    }
    this.setState({
      data: temp,
            
    });
          console.log(temp);
    
    this.closeActivityIndicator();
    this._carousel.scrollToIndex({index:0});
    console.log("loaded");
  }

}
}


<Carousel
data={this.state.data}
keyExtractor={(item, index) => index.toString()}
renderItem={this._renderItem.bind(this)}
itemWidth={wp('100%')}
containerWidth={wp('100%')}
itemContainerStyle={{height:hp('80%'),}}
separatorWidth={0}
ref={(c) => {
this._carousel = c;
}}
initialIndex={0}
initialScrollIndex={0}
onScrollEnd={() => console.log("scrolling")}
initialNumToRender={10}

        />

How to fix it?

No Autoplay?

Somehow I was not able to find a property for autoPlay. Is there one?

Disabled swipe mode ?

Hello @lehoangnam97

Thank for your great module 💪

I was wondering if the enableSwip props was available ? This is usually a rather popular feature. If it's not present, maybe I'll do a RM if it suits you :)

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.