Search code examples
javascriptreactjsreact-nativereact-native-snap-carousel

how to make carousel circular in react-native-snap-carousel?


I have a simple carousel that has 5 images in it. After reaching the 5th image, I want it to go to first image and start again. I tried to solve it by reading documentation, but I can't see anything that could help. I have also tried looking online for some examples, but there coluldn't find it.

import React from 'react';
import { StyleSheet, Text, View, Image} from 'react-native';
import Carousel from 'react-native-snap-carousel';

const data = [
  {
      key:1,
    uri: 'https://i.ibb.co/hYjK44F/anise-aroma-art-bazaar-277253.jpg',
    title: 'Lorem ipsum dolor sit amet',
    content: 'Neque porro quisquam est qui dolorem ipsum quia '
  },
  
];
export default class App extends React.Component {
    
  _renderItem ({item, index}) {
      const { uri, title, content } = item;
        return (
        
            <View style={styles.slide}>
                
                <Image
          source={{ uri: uri }}
          style={styles.imageBackground}
       / >
                
            </View>
            
        );
    }

    render () {
        return (
        <View style={styles.container}>
            <Carousel
              ref={(c) => { this._carousel = c; }}
              data={data}
              renderItem={this._renderItem}
              sliderWidth={300}
              itemWidth={300}
              autoplay={true}
              
            />
            </View>
        );
    }
}


and here is my package.json file

  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "expo": "~38.0.1",
    "expo-status-bar": "^1.0.0",
    "react": "~16.11.0",
    "react-dom": "~16.11.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-38.0.0.tar.gz",
    "react-native-snap-carousel": "^3.9.1",
    "react-native-web": "~0.11.7"
  },
  "devDependencies": {
    "@babel/core": "^7.8.6",
    "babel-preset-expo": "~8.1.0"
  },
  "private": true
}

Autoscroll is working fine.


Solution

  • You've missed loop={true} this attribute in your Carousel.

    <Carousel
      ref={(c) => { this._carousel = c; }}
      data={data}
      renderItem={this._renderItem}
      sliderWidth={300}
      itemWidth={300}
      autoplay={true}
      loop={true}
    />
    

    There is another attribute named enableSnap which is true by default. If it is set to false, loop attribute won't work.