nadeshoki
nadeshoki

Reputation: 371

how to handle Onpress events in react native snap carousel

I have a class and in that class I am displaying carousel components like this

sampleclass.js

.
.
. 
render{
return (
<Image ..> 
<Text>
text 
</Text>
<Image ..>
<js file tag where carousel is defined />
</Image>

<Text>
text 
</Text>
<Image ..>
<js file tag where carousel is defined />
</Image>
.
.
.
</Image>
);
}

function fname(params..){
I also need to access carousel ref here 
}

and I have another class where I have defined the carousel

carouselclass.js

import React, { PureComponent } from 'react';
import { Dimensions, StyleSheet, View } from 'react-native';

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

export default class ExampleCarousel extends PureComponent {
    state = {
        data: [{}, {}, {}, {}, {}, {}]
    }

    renderItem = () => (
        <View style={styles.tile} />
    );

    render () {
        return (
            <View style={styles.container}>
                <Carousel
                  data={this.state.data}
                  renderItem={this.renderItem}
                  itemWidth={Dimensions.get('window').width * 0.85}
                  sliderWidth={Dimensions.get('window').width}
                  containerCustomStyle={styles.carousel}
                  slideStyle={{ flex: 1 }}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        height: 300
    },
    carousel: {
        flex: 1,
        backgroundColor: 'red'
    },
    tile: {
        flex: 1,
        width: Dimensions.get('window').width * 0.85,
        backgroundColor: 'yellow'
    }
});

I have to handle the onPress event of the carousel swipe components in the function of sampleclass.js

How can I do this I know how to handle onPress events on react native but couldnt do this with react-native-snap-carousel since I am using it for the first time I have read examples given in the docs but couldnt find something related to this

Upvotes: 2

Views: 7217

Answers (2)

Lauro Vitor
Lauro Vitor

Reputation: 1

<Carousel
...
  renderItem={(carousel, parallaxProps) =>
    this._renderItem(carousel, parallaxProps)
}
...
/>


_renderItem(carousel, parallaxProps) {
  const { item } = carousel;
  return (
    <TouchableOpacity
      onPress={() => {
        this._handlePress(item._id);
      }}
    >
    ...

Upvotes: 0

bennygenel
bennygenel

Reputation: 24680

If you want to handle single Carousel item's onPress prop, you need to add that to your render item.

Example

// change this
renderItem = () => (
    <View style={styles.tile} />
);

// to this
_onPressCarousel = () => {
    // here handle carousel press
}
renderItem = () => (
    <TouchableOpacity onPress={this._onPressCarousel} style={styles.tile}>
        <Image
            style={styles.button}
            source={require('./myButton.png')}
        />
    </TouchableOpacity>
);

Upvotes: 3

Related Questions