0

I'm trying to highlight an indicator based on the active item of a flatlist , How i'm trying to do it is like this :

 const [activeIndex, setActiveIndex] = useState(0);
  const windowWidth = useWindowDimensions().width;

  const onFlatlistUpdate = useCallback(({ viewableItems }: any) => {
    if (viewableItems.length > 0) {
      setActiveIndex(viewableItems[0].index);
    }
    console.log(viewableItems);
  }, []);

  const renderItem: ListRenderItem<string> = ({ item }) => {
    return (
      <Image
        style={[styles.image, { width: windowWidth - 40 }]}
        source={{ uri: item }}
      />
    );
  };

  return (
    <View style={styles.root}>
      <FlatList
        keyExtractor={(key) => key}
        decelerationRate="fast"
        snapToInterval={windowWidth - 20}
        snapToAlignment="center"
        data={images}
        renderItem={renderItem}
        horizontal
        showsHorizontalScrollIndicator={false}
        viewabilityConfig={{
          viewAreaCoveragePercentThreshold: 50,
        }}
        onViewableItemsChanged={onFlatlistUpdate}
      />

I'm using a callback so don't get the changing onviewableitems on the fly isn't supported but it seems like the

<View style={styles.dots}>
    {images.map((image, index) => (
      <View
        style={[
          styles.dot,
          {
            backgroundColor: index === activeIndex ? "#c9c9c9" : " #ededed",
          },
        ]}
      />
    ))}
  </View>

when i change the item on the flatlist the chosen item becomes highlighted and all previous highlighted items are also highlighted if that makes sense , so if i'm on the first image of the flatlist the first dots is highlighted

Mohamed Nabil
  • 525
  • 2
  • 9
  • 24
  • Does this answer your question? [How to get currently visible index in RN flat list](https://stackoverflow.com/questions/45868284/how-to-get-currently-visible-index-in-rn-flat-list) – Youssouf Oumar Jul 23 '22 at 15:51

1 Answers1

0

Render item provides an index prop to your component

 const renderItem: ListRenderItem<string> = ({ item, index }) => {
Poptocrack
  • 2,879
  • 1
  • 12
  • 28