Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native carousel item active index

I've just started learning react native and I want to make a splash screen that contains a slider with dots. But when I scroll the scrollview the active dot doesn't change properly. My slider component is like below

export default function Slider() {
  const [active, setActive] = useState(0);

  const onChange = ({ nativeEvent }) => {
    const active = Math.floor(
      nativeEvent.contentOffset.x / nativeEvent.layoutMeasurement.width
    );

    setActive({ active });

    console.log(active);
   
  };

  return (
    <View style={styles.container}>
      <ScrollView
        onMomentumScrollEnd={onChange}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
      >
        {dummyData.map((item, index) => {
          return (
            <SliderItem
              key={index}
              title={item.title}
              image={item.url}
              description={item.description}
            />
          );
        })}
      </ScrollView>
      <View style={styles.dotView}>
        {dummyData.map((k, i) => (
          <View
            key={i}
            style={{
              backgroundColor: i === active ? "red" : "blue", // My problem is here
              height: 10,

              width: 10,

              margin: 8,
              borderRadius: 6,
            }}
          />
        ))}
      </View>
    </View>
  );
}
like image 565
Oğulcan Karayel Avatar asked Oct 29 '25 13:10

Oğulcan Karayel


1 Answers

Change setActive({ active }); to setActive(active);

like image 56
D10S Avatar answered Oct 31 '25 11:10

D10S