From 33d6da01ea15022485d8e65beae49a779130921a Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Wed, 2 Aug 2023 21:13:43 -0700 Subject: [PATCH] Cache ScrollView content length before calling `scrollToIndex` (#38736) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/38736 `scrollToIndex` relies on cached layout information, so we should cache the results from `onContentSizeChange` before attempting the scroll. Otherwise we will fail to scroll in RTL. Changelog: [General][Fixed] Cache ScrollView content length before calling `scrollToIndex` Reviewed By: lenaic Differential Revision: D47978635 fbshipit-source-id: 27f2a4702650e8a73e8812128821ca03f36216dd --- .../Lists/VirtualizedList.js | 38 +++++++++++++------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/packages/virtualized-lists/Lists/VirtualizedList.js b/packages/virtualized-lists/Lists/VirtualizedList.js index dd55541571f308..350e500e1e0d01 100644 --- a/packages/virtualized-lists/Lists/VirtualizedList.js +++ b/packages/virtualized-lists/Lists/VirtualizedList.js @@ -1608,9 +1608,32 @@ class VirtualizedList extends StateSafePureComponent { } _onContentSizeChange = (width: number, height: number) => { + this._listMetrics.notifyListContentLayout({ + layout: {width, height}, + orientation: this._orientation(), + }); + + this._maybeScrollToInitialScrollIndex(width, height); + + if (this.props.onContentSizeChange) { + this.props.onContentSizeChange(width, height); + } + this._scheduleCellsToRenderUpdate(); + this._maybeCallOnEdgeReached(); + }; + + /** + * Scroll to a specified `initialScrollIndex` prop after the ScrollView + * content has been laid out, if it is still valid. Only a single scroll is + * triggered throughout the lifetime of the list. + */ + _maybeScrollToInitialScrollIndex( + contentWidth: number, + contentHeight: number, + ) { if ( - width > 0 && - height > 0 && + contentWidth > 0 && + contentHeight > 0 && this.props.initialScrollIndex != null && this.props.initialScrollIndex > 0 && !this._hasTriggeredInitialScrollToIndex @@ -1630,16 +1653,7 @@ class VirtualizedList extends StateSafePureComponent { } this._hasTriggeredInitialScrollToIndex = true; } - if (this.props.onContentSizeChange) { - this.props.onContentSizeChange(width, height); - } - this._listMetrics.notifyListContentLayout({ - layout: {width, height}, - orientation: this._orientation(), - }); - this._scheduleCellsToRenderUpdate(); - this._maybeCallOnEdgeReached(); - }; + } /* Translates metrics from a scroll event in a parent VirtualizedList into * coordinates relative to the child list.