Reputation: 68
I'd like to add a SectionList to my app such that it renders to a specific section (that isn't the first section in the list). Calling scrollToLocation on componentDidMount does not work; however, adding a button that calls scrollToLocation does. Is there a reason for this?
Could this be due to the SectionList reference (I've tried a few approaches for assigning reference, e.g. variable assignment, function assignment, using createRef, etc.)?
Here is a link to a stripped-down Expo snack to illustrate what I mean: https://snack.expo.io/@bobbymoogs/scrolltolocation-on-componentdidmount.
Upvotes: 1
Views: 928
Reputation: 264
I found the best solution on this thread is to use onLayout
to trigger the scroll:
scrollToInitialPosition = () => {
this.scrollViewRef.scrollTo({ y: 100 });
}
...
<ScrollView
ref={(ref) => { this.scrollViewRef = ref; }}
onLayout={this.scrollToInitialPosition}
/>
Note there are lots of other suggestions using setTimeout
, componentDidUpdate
, InteractionManager
, etc. However using onLayout was the only one that worked for me (and also seems to me to be the cleanest).
Upvotes: 4