'React-Native panResponder array with functional component
I have a slider with 6 images and I want to be able to move each one of them using panResponder.
I wrote this code (which works, but it moves all the slider, not just one image)
const pan = useState(new Animated.ValueXY())[0];
const panResponder = useState(
PanResponder.create({
onMoveShouldSetResponderCapture: () => true, //Tell iOS that we are allowing the movement
onMoveShouldSetPanResponderCapture: () => true, // Same here, tell iOS that we allow dragging
onMoveShouldSetPanResponder: () => true,
onPanResponderGrant: (e, gestureState) => {
pan.setOffset({
y: pan.y._value
});
},
onPanResponderMove: Animated.event(
[
null,
{ dy: pan.y }
],
{
useNativeDriver: false,
listener: (evt, gestureState) => {
}
}
),
onPanResponderRelease: (evt, gestureState) => {
//pan.flattenOffset();
console.log(gestureState);
if (gestureState.moveY > 710) {
Alert.alert("Added to cart.");
}
else {
Animated.spring(pan, {
toValue: 100,
useNativeDriver: false
},
).start();
}
}
})
)[0];
return (
<View style={styles.container}>
<View style={{ width, height: '100%' }}>
<ScrollView
horizontal
style={{ width }}
showsHorizontalScrollIndicator={false}
>
{
products.map((product) => (
<Animated.View key={product.id}
style={{
transform: [{ translateY: pan.y }]
}}
{...panResponder.panHandlers}
>
<Image
style={{ width: width / 3, height, flex: 1 }}
resizeMode="contain"
source={{
uri: product.product_image,
}}
/>
</Animated.View>
))
}
</ScrollView>
</View>
<View style={styles.cart}>
<Text style={styles.cartText}>Here comes the cart</Text>
</View>
</View >
);
}
I want to be able to drag every image, not the whole slider. Is it possible? I understand we need an array of panResponders, but how to actually do it?
Many thanks
Solution 1:[1]
what you have to do for. everyone. image transform it into a single component, and to each of them add a panResponder , if you do it with only one, it takes the entire current component to raise the event
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | furto ferto |