How to implement a carousel in react-native with custom navigators.

React native is awesome, it makes life easier for mobile application developers.  It allows you to have the same codebase for your Android and iOS apps. Developing with react-native using Expo is a lot more fun and easier, we will be using expo in the demos of this tutorial.

We will implement a carousel in react-native with custom navigators that will work cross-platform. Here is what our carousel looks like:

react native carousel demo

 

Following are the steps we will follow to get the desired result as above

  1. Install and setup react native
  2. Install dependencies
  3. Implement simple carousel
  4. Implement custom navigation for the carousel

 

Step 1: Install and setup react native

You can follow the official getting started guide by the Facebook team given here: https://facebook.github.io/react-native/docs/getting-started.html. We assume that you have npm installed and running if you don't, please install it and then continue with this tutorial.

Run npm install -g expo-cli to install expo.

Then run expo init rncarouseldemo
and follow the instructions to create your demo project. It will ask you for a few details, you can select the pre-selected values from the options and wait for it to finish.

Change into the project directory by running cd rncarouseldemo or whatever your project directory is.

Step 2: Install dependencies

We will be using this project on Github to implement our carousel, so let us import this dependency using npm.

Run npm install --save react-native-snap-carousel
npm will download and save the dependency in node_modules directory and it will become available for us to use in our project.

 

Step 3: Implement simple carousel

Open App.js and add the following code

import React from 'react';
import { StyleSheet,Text, Image, View,SafeAreaView} from 'react-native';

import Carousel from 'react-native-snap-carousel';

export default class App extends React.Component {
 
    constructor(props){
        super(props);
        this.state = {
            carouselItems: [
            {
                title:"Item 1"
            },
            {
                title:"Item 2"
            },
            {
                title:"Item 3"
            },
            {
                title:"Item 4"
            },
            {
                title:"Item 5"
            }
        ]}
    }

    _renderItem({item,index}){
        return (
            <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>                 
                <Text style={{color:'#fff'}} >{item.title}</Text>
            </View>
        )
    }

    render() {
        return (
        <SafeAreaView style={styles.container}>


          
            <Carousel
                    data={this.state.carouselItems}
                    sliderWidth={250}
                    itemWidth={250}
                    renderItem={this._renderItem}
                />
           

        </SafeAreaView>
        );
    }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor:'#131420',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

If you run your app now with the code given above in App.js, you are expected to get a simple carouse. How did the magic happen? I have explained that in the video (at the bottom of this post) line by line. If you know the basics of react-native you will not have difficulty understanding this code.

The only new thing here is the Carousel component, full documentation for this component and its various features can be found here: https://github.com/archriss/react-native-snap-carousel.

Adding an image  in the _renderItem view:

_renderItem({item,index}){
    return (
        <View style={{flex:1,justifyContent:'center',alignItems:'center'}}> 
            <Image
                source={require('./assets/usericon.png')}
                />
            <Text style={{color:'#fff'}} >{item.title}</Text>
        </View>
    )
}

we get the following result:

reatc-native-carousel-simple

 

Step 4: Implement custom navigation for the carousel

Replace the render function to include two arrow buttons for our custom navigation:

render() {
    return (
    <SafeAreaView style={styles.container}>


        <TouchableHighlight
            onPress={
                () => { this.carousel._snapToItem(this.state.activeIndex-1)}
            }>
            <Image source={require('./assets/leftarrow.png')}/>
        </TouchableHighlight>

        <View>
            <Carousel

                    ref={ref => this.carousel = ref}
                    data={this.state.carouselItems}
                    sliderWidth={250}
                    itemWidth={250}
                    renderItem={this._renderItem}
                    onSnapToItem = { index => this.setState({activeIndex:index}) }
                />
        </View>

        <TouchableHighlight            
            onPress={
                () => { this.carousel._snapToItem(this.state.activeIndex+1)}
            }>
            <Image source={require('./assets/rightarrow.png')}/>                
        </TouchableHighlight>

        

    </SafeAreaView>
    );
}

Also, change the flexDirection for styles.container to "row", as following:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection:'row', //add this
    backgroundColor:'#131420',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

So that all the elements in the container are placed in the same row. Now run your app and you should get the following with fully functional custom navigation arrows:

react native carousel demo

 

Full source code with all the assets used in the example is available on this git repository: hack4mer/react-native-carousel-demo

Watch it:

Comments