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

react-native-snap-corousel: How to call a function on item click


I want to call a function on clicking of an Item in corousel. below is my code.

    onPress(){
       console.log("onPress");
    }
    _renderItem({item, index}) {
    return (
        <TouchableWithoutFeedback
          onPress={this.onPress.bind(this)}>
          <View style={styles.slide}>
            <Image
              source={{ uri: item.row.image_name }}
              style={styles.image}
            />

          </View>
        </TouchableWithoutFeedback>
      );
  }

When I click the item I am getting error saying _this6.onPress is not a function.

I am able to alert directly on click like below.

<TouchableWithoutFeedback onPress={()=>{ Alert.alert("onPress");}}>

How can I call a method on Item click?

demo code: https://snack.expo.io/SJtm1vJMX


Solution

  • All of your functions need to be bound not to loose context of this. This means you need to do this._renderItem.bind(this) too.

    Sample (removed some parts for simplicity)

    export default class ImageCarousel extends Component {
      constructor(props) {
        super(props);
        this.state = {
          slider1ActiveSlide: SLIDER_1_FIRST_ITEM,
        };
        this._renderItem = this._renderItem.bind(this);
        this.onPress = this.onPress.bind(this);
      }
      onPress() {
        Alert.alert('Hi');
      }
      _renderItem({ item, index }) {
        return (
          <TouchableOpacity onPress={this.onPress}>
            <Image style={styles.image} source={{ uri: item.illustration }} />
          </TouchableOpacity>
        );
      }
    
      mainExample(number, title) {
        const { slider1ActiveSlide } = this.state;
        return (
          <View>
            <Carousel
              ref={c => (this._slider1Ref = c)}
              data={ENTRIES1}
              renderItem={this._renderItem}
              {/* ... */}
            />
            {/* ... */}
          </View>
        );
      }
    
      render() {
        const example1 = this.mainExample(
          1,
          'Default layout | Loop | Autoplay | Scale | Opacity | Pagination with tappable dots'
        );
        return <ScrollView>{example1}</ScrollView>;
      }
    }