9

I need set initialScrollIndex on FlatList to 1, so second row will be visible on initial loading. It's depend on getItemLayout. My FlatList cells contains text of different length, which leads to different height of each cell, which leads i can not return fixed value in getItemLayout. My strategy is:

  1. On load, iterate through dataset for list and calculate height of each row
  2. Cache calculated data into array or dictionary
  3. Return cached data inside getItemLayout depend on index

The problem is - i can not find the way how to calculate the height of an view before it will be mounted into DOM hierarchy. I read a lot about onLayout prop, but it looks like View should be rendered first to get it to work.

So, what do you use to achieve scrolling to specified row in react-native when list cell is not the same for each row?

George
  • 643
  • 9
  • 23
  • I dont think there is a way to get width or height of your component before it is rendered. But if there is i am here to learn :) – Kaan Öner Jan 02 '18 at 08:34

2 Answers2

1

My first thought - try render it hidden, take size and make it visible.

EDIT: You also can try use react-native-text-size to calculate cell heights manually.

Alexander Danilov
  • 3,038
  • 1
  • 30
  • 35
  • In response of that thought my first thought is efficiency of this solution. If RN can render items with dynamic height finally under the hood, why we need to provide it explicitly for scrollToIndex or scrollToItem to be working? In case we can omit efficiency, do you know link to resource with example of rendering hidden items? I can not find anything relative. – George Feb 26 '18 at 08:44
  • @George you can try set opacity:0 or add view with background color on the top of flat list with absolute position or any other hack. – Alexander Danilov Feb 27 '18 at 09:23
  • @George or move view from screen { y: screenHeight }. Lots of options ;) – Alexander Danilov Feb 27 '18 at 09:33
  • The question is now a year old, and there is still a surfeit of solutions. I was able to pre-render all my items to get the view heights, but this process takes 10+ minutes for my FlatList (18000 items). In any case, here is a link to my code and answer wherein I get the code to properly iterate and provide the dimensions via pre-rendering. https://stackoverflow.com/questions/54561979/problem-iterating-through-calls-to-onlayout-for-providing-dimensions-of-variable/ – simplegr33n Feb 07 '19 at 03:05
-3

Try setting scrollToIndex or scrollToItem in your flat list

https://facebook.github.io/react-native/docs/flatlist.html#scrolltoindex

see the other methods you can use to scroll to a specific location on your list https://facebook.github.io/react-native/docs/flatlist.html#methods

  • yaniv-shnaider `scrollToIndex` as well as `scrollToItem` does't work without `getItemLayout` to be implemented. How to implement `getItemLayout` for items with dynamic height is the subject of my question. – George Feb 26 '18 at 08:39