Search code examples
react-nativereact-native-flatlist

How to go to a specific item(index) in FlatList


I saw this, but I could not do. I have a static list named DAYS and bind it to the FlatList as below :

const DAYS = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
]

const App = () => {
  const onViewRef = useRef((viewableItems) => {
  })

  const viewConfigRef = useRef({ viewAreaCoveragePercentThreshold: 50 })

  return (
    <View style={styles.screen}>

      <Button title="Go To" onPress={() => { }} />
      <FlatList
        data={DAYS}
        horizontal={true}
        showsHorizontalScrollIndicator={false}
        keyExtractor={(item, index) => index.toString()}
        onViewableItemsChanged={onViewRef.current}
        viewabilityConfig={viewConfigRef.current}
        renderItem={({ item }) =>
          <View style={styles.textContainer}>
            <Text style={styles.text}>{item}</Text>
          </View>}
      />

    </View>
  )
}

after running :

enter image description here

Now, when I click on the button(GO TO), FlatList should be as below :

(for example go to item 10,Selected Item should be center)

enter image description here


Solution

  • By reading scrollToIndex and getItemLayout probably you can do:

    const DAYS = [
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
    ]
    
    const ITEM_WIDTH = 20 // size of you element
    
    const App = () => {
      const flatListRef = useRef(null)
    
      const onViewRef = useRef((viewableItems) => {
      })
    
      const viewConfigRef = useRef({ viewAreaCoveragePercentThreshold: 50 })
    
      return (
        <View style={styles.screen}>
    
          <Button title="Go To" onPress={() => {
            if (flatListRef.current) {
                flatListRef.current.scrollToIndex({index: 9}) // Scroll to day 10
            }
          }} />
          <FlatList
    
            ref={flatListRef} // add ref
            getItemLayout={(data, index) => (
              {length: ITEM_WIDTH, offset: ITEM_WIDTH * index, index}
            )}
    
            data={DAYS}
            horizontal={true}
            showsHorizontalScrollIndicator={false}
            keyExtractor={(item, index) => index.toString()}
            onViewableItemsChanged={onViewRef.current}
            viewabilityConfig={viewConfigRef.current}
            renderItem={({ item }) =>
              <View style={styles.textContainer}>
                <Text style={styles.text}>{item}</Text>
              </View>}
          />
    
        </View>
      )
    }