DEV Community

loading...

How can I use refs to set callbacks on a FlatList?

technoplato profile image Michael Lustig - halfjew22@gmail.com ・Updated on ・1 min read

StackOverflow Post

I'm trying to use refs to set the onEndReached prop of my FlatList imperatively. Is there a way to do that?

I've modified an example from the PR that adds setNativeProps that toggles the color from black to white on an interval, but can't get onEndReached or onScroll to be called.

Can anyone help me understand what I'm doing wrong?

export default class Testing extends React.Component {
  componentDidMount() {
    let tick = 0
    this.list.setNativeProps({
      onEndReached: info => {
        // NEVER CALLED 😒
        console.log('L231 on Scroll info ===', info)
      },

      onScroll: info => {
        // NEVER CALLED 😒
        console.log('L250 info ===', info)
      },

      // Background DOES flash red on load... πŸ€” 
      style: { backgroundColor: 'red' }
    })
    setInterval(() => {
      this.list.setNativeProps({
        onEndReached: info => {
          console.log('L231 on Scroll info ===', info)
        },

        // Background DOES toggle black and white... πŸ€” 
        style: { backgroundColor: tick++ & 2 ? 'white' : 'black' }
      })
    }, 1000)
  }

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          ref={component => (this.list = component)}
          style={{ backgroundColor: 'black' }}
          data={[{ key: 'a' }, { key: 'b' }]}
          renderItem={({ item }) => <Text>{item.key}</Text>}
        />
      </View>
    )
  }
}

Discussion

pic
Editor guide