nicholas
nicholas

Reputation: 14563

Setting an initial scroll position of a React Native ListView

I'm trying to set the initial scroll position of a ListView in react native.

Right now, I'm doing this:

componentDidMount() {
  let i = this.props.images.indexOf(this.props.current);
  if(i != -1) {
    this.refs.listView.scrollTo({ x:i*this.props.width, y:0, animated:false });
  }
}

where the images prop is the datasource for the ListView, the current prop is where I want to be initially scrolled to, and the width prop is the width of the component. (The component scrolls horizontally).

This works, but there's a delay between the initial render and the call to componentDidMount, giving me a flash of the end of end of the list before the list is scrolled.

Is there a way of setting an initial scroll position of the list? Or better way of doing this to get rid of that flash?

Upvotes: 5

Views: 23575

Answers (1)

jevakallio
jevakallio

Reputation: 35890

On iOS you can use the ScrollView#contentOffset to set the initial scroll position of a ListView, which inherits the properties of ScrollView.

If you are looking for an Android solution, the ListView.scrollTo method you are calling seems like the best bet for the general case.

That said, if I interpret your code sample correctly, you are using the ListView for a paginated, horizontal list, perhaps with the help of the pagingEnabled property? If this is the case, on Android you might look at using ViewPagerAndroid instead, and setting the initialPage property.

Upvotes: 7

Related Questions