user7917760
user7917760

Reputation:

React-native: FlatList get refs to scroll

I'm currently building an app with react native:

this is my flatlist:

    <FlatList
      ref={"myFlatList"}
      data={data}
      keyExtractor={this._keyExtractor}
      renderItem={this._renderItem}
    />

In this function I want to scroll to a specific index:

  _enableTVEventHandler() {
    this._tvEventHandler = new TVEventHandler();
    this._tvEventHandler.enable(this, function(cmp, evt) {
        this.refs["myFlatList"].scrollToIndex({viewPosition: 0.5, index: 2});
    }.bind(this));
  }

But I have an error: Cannot read property 'scrollToIndex' of undefined

Upvotes: 3

Views: 25296

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281646

Two things that I can see,

  1. You need not define string refs within {}. However React docs suggest you to make use of ref callback

Do it something like

 <FlatList
      ref={(list) => this.myFlatList = list}
      data={data}
      keyExtractor={this._keyExtractor}
      renderItem={this._renderItem}
    />
  1. You need to bind your function to be able to refer to the correct context

Do it like

_enableTVEventHandler = () => {
    this._tvEventHandler = new TVEventHandler();
    this._tvEventHandler.enable(this, function(cmp, evt) {
        this.myFlatList.scrollToIndex({viewPosition: 0.5, index: 2});
    }.bind(this));
  }

or

constructor(props) {
    super(props) ;
    this._enableTVEventHandler = this._enableTVEventHandler.bind(this); 
}

Upvotes: 4

Related Questions