From 921c9ff165d47a73e9978df918b1761b95f9979d Mon Sep 17 00:00:00 2001 From: Kacie Bawiec Date: Wed, 3 Mar 2021 15:16:15 -0800 Subject: [PATCH] Fix sticky header not sticking on first render in ScrollView Summary: # The bug Sticky headers would not "stick" to the top of the ScrollView on initial render. On subsequent redners, all sticking would work correctly. # Why the bug existed This code to initialize the animated values used for sticky headers was in `UNSAFE_componentWillMount` prior to D26375818 (https://github.com/facebook/react-native/commit/1641d46529f33a1726b5c4f3429655314386c064). `UNSAFE_componentWillMount` is called before `render`. In D26375818 (https://github.com/facebook/react-native/commit/1641d46529f33a1726b5c4f3429655314386c064), I moved the code into `componentDidMount`, which is called after `render`. This caused a problem because code in `render` was relying on these initializations being done already. # How I resolved the bug To resolve this, I initialize these values in the constructor. # Reference Docs for React mount ordering: https://reactjs.org/docs/react-component.html#mounting Changelog: [General][Fixed] Fix sticky header not sticking on first render in ScrollView Reviewed By: nadiia Differential Revision: D26792003 fbshipit-source-id: c575e8cdd1d986ce3c38941d95d763e329e74874 --- Libraries/Components/ScrollView/ScrollView.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Libraries/Components/ScrollView/ScrollView.js b/Libraries/Components/ScrollView/ScrollView.js index a5f17fe18890bb..155bc3444e5837 100644 --- a/Libraries/Components/ScrollView/ScrollView.js +++ b/Libraries/Components/ScrollView/ScrollView.js @@ -719,6 +719,13 @@ class ScrollView extends React.Component { static Context: typeof ScrollViewContext = ScrollViewContext; constructor(props: Props) { super(props); + + this._scrollAnimatedValue = new AnimatedImplementation.Value( + this.props.contentOffset?.y ?? 0, + ); + this._scrollAnimatedValue.setOffset(this.props.contentInset?.top ?? 0); + this._stickyHeaderRefs = new Map(); + this._headerLayoutYs = new Map(); } _scrollAnimatedValue: AnimatedImplementation.Value = new AnimatedImplementation.Value( @@ -789,13 +796,6 @@ class ScrollView extends React.Component { this.scrollResponderKeyboardDidHide, ); - this._scrollAnimatedValue = new AnimatedImplementation.Value( - this.props.contentOffset?.y ?? 0, - ); - this._scrollAnimatedValue.setOffset(this.props.contentInset?.top ?? 0); - this._stickyHeaderRefs = new Map(); - this._headerLayoutYs = new Map(); - this._updateAnimatedNodeAttachment(); }