Search code examples
reactjsreact-nativecarouselreact-native-snap-carousel

Can't use react-native-snap-carousel


I would like use react-native-snap-carousel but when I try to init in I have an error :(

the exemple :

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

export class MyCarousel extends Component {

_renderItem ({item, index}) {
    return (
        <View style={styles.slide}>
            <Text style={styles.title}>{ item.title }</Text>
        </View>
    );
}

render () {
    return (
        <Carousel
          ref={(c) => { this._carousel = c; }}
          data={this.state.entries}
          renderItem={this._renderItem}
          sliderWidth={sliderWidth}
          itemWidth={itemWidth}
        />
    );
}}

My code :

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

export default class App extends React.Component {
 _renderItem ({item, index}) {
   return (
      <View style={styles.slide}>
          <Text style={styles.title}>{ item.title }</Text>
      </View>
);}
 render () {
   return (
    <Carousel
      ref={(c) => { this._carousel = c; }}
      data={this.state.entries}
      renderItem={this._renderItem}
      sliderWidth={150}
      itemWidth={100}
    />
); 
}} 
    const styles = StyleSheet.create({
     container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
   }});

Screenshot the same on app.js react Native

I'have see a issue (the same like me) link to Github Issue

But not answer and issue be close


Solution

  • As the screenshot says, this.state.entries is null.

    You must initialize it :

    export default class App extends React.Component {
      constructor() {
        super()
        this.state = {
          entries: [],
        }
      }
      _renderItem ({item, index}) {
        return (
          <View style={styles.slide}>
              <Text style={styles.title}>{ item.title }</Text>
          </View>
      );}
    
      render () {
        return (
          <Carousel
            ref={(c) => { this._carousel = c; }}
            data={this.state.entries}
            renderItem={this._renderItem}
            sliderWidth={150}
            itemWidth={100}
          />
     ); 
    }}
    

    In this example, entries: [] wont display anything since there's no object in it. You can initialize it with wanted data:

    entries: [
      { title: 'hello' },
      { title: 'world' },
    ]
    

    Btw, this issue has nothing to do with the plugin itself, even if they could catch it.