javascript – Parallax effect using Animated not working in React Native ScrollView


I’m currently working on a React Native project where I’m trying to implement a parallax effect for images inside a horizontal ScrollView using the Animated module. However, I’m facing issues, and the parallax effect doesn’t seem to work as expected.

Here’s a simplified version of my code:

// Relevant imports...

const SliderView = ({ items }) => {
  const scrollX = useRef(new Animated.Value(0)).current;

  return (
    <ScrollView
      horizontal
      showsHorizontalScrollIndicator={false}
      onScroll={Animated.event(
        [{ nativeEvent: { contentOffset: { x: scrollX } } }],
        { useNativeDriver: false }
      )}
      scrollEventThrottle={16}
    >
      {items.map((item, index) => {
        const inputRange = [(index - 1) * 300, index * 300, (index + 1) * 300];
        const translateX = scrollX.interpolate({
          inputRange,
          outputRange: [50, 0, -50], // Adjust these values as needed
        });

        console.log('scrollX', scrollX);
        console.log('translateX', translateX);

        return (
          <Animated.View key={item.id} style={{ transform: [{ translateX }], marginLeft: index === 0 ? 20 : 0 }}>
            <Image source={{ uri: item.image }} style={{ width: 300, height: 200, borderRadius: 10 }} />
            <View style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: 10 }}>
              <Text style={{ color: 'white', fontSize: 18, fontWeight: 'bold' }}>{item.title}</Text>
              <Text style={{ color: 'white', fontSize: 14 }}>{item.subTitle}</Text>
            </View>
          </Animated.View>
        );
      })}
    </ScrollView>
  );
};



Despite my efforts, the parallax effect doesn’t seem to work correctly. The console logs for scrollX and translateX show unexpected values.

I would appreciate any insights or suggestions on what might be causing this issue and how to resolve it. Thank you!

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img