I'm using React Native and I'm having trouble retaining vertical centering of elements as soon as I introduce a ScrollView. To demonstrate, I created 3 apps with React Native Playground. All examples have 2 pages, and they can be toggled by tapping the blue button.
Example 1:
This first example shows blocks centered vertically on page 2. This happens because the container has these styles applied to it:
flex: 1, flexDirection: 'column', justifyContent: 'center',
https://rnplay.org/apps/lb5wSQ
However, there's a problem as soon as you switch to page 2, because the entire content of the page doesn't fit, so we need a ScrollView
.
Example 2
In this example, I wrap everything inside of a ScrollView. This allows page 2 to scroll, but now I lost the vertical centering of Page 1.
https://rnplay.org/apps/DCgOgA
Example 3
In order to try and get back the vertical centering of Page 1, I apply flex: 1
to the contentContainerStyle
of ScrollView. This fixes the vertical centering on page 1, but I'm no longer able to scroll all the way down to the bottom on page 2.
https://rnplay.org/apps/LSgbog
How can I fix this so that I get vertical centering of elements on page 1 yet still get ScrollView to scroll all the way to the bottom on page 2?
To scroll to top of the ScrollView with React Native, we assign a ref to the ScrollView and call scrollTo on the ref's value. to create a ref with useRef and set that as the value of the ref prop of the ScrollView . Then we add a Button that calls ref. current.
ScrollView renders all its react child components at once, but this has a performance downside. FlatList renders items lazily, when they are about to appear, and removes items that scroll way off-screen to save memory and processing time.
I solved this issue with flexGrow instead of flex
<ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }}>
This makes the content container stretch to fill the ScrollView but does not restrict the maximum height, so you can still scroll correctly when the content extends the bounds of the ScrollView
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With