Sydney C.
Sydney C.

Reputation: 978

How to use ReactNative FlatList ScrolltoIndex properly?

I'm a newbie in react native and I'm running into an issue I didn't manage to solve by myself.

So far this is how I am using it:

export default class Form extends React.Component {
  state = {index: 0};

  _keyExtractor = (item, index) => item.id;

  myscrollToIndex = () => {
    this.setState({index: ++this.state.index});
    this.flatListRef.scrollToIndex({animated: true,index: this.state.index});
  };

  _renderItem = ({item}) => (
    <View>
      <Question {...item} />
      <Button label='Next' onPress={this.myscrollToIndex} style={styles.buttonNext}/>
    </View>
  )

  render() {
    return (
      <View style={styles.container}>
      <FlatList
        horizontal={false}
        ref={(ref) => { this.flatListRef = ref; }}
        scrollEnabled
        data={this.props.form}
        extraData={this.state}
        keyExtractor={this._keyExtractor}
        renderItem={this._renderItem} />
      </View>
    );
  }
}

I would like to pass the index to myscrolltoindex function but I don't manage to as this.flatListRef gets ruled out when I do that.

Have anyone run into a similar issue ?

Thank you for your time

Upvotes: 5

Views: 8740

Answers (1)

Vivek_Neel
Vivek_Neel

Reputation: 1353

Use index param as well. And pass the index around.

For e.g _renderItem = ({item, index}) => ( <View> <Question {...item} /> <Button label='Next' onPress={this.myscrollToIndex(index) } style={styles.buttonNext}/> </View> )

Upvotes: 4

Related Questions