Set contentInset and contentOffset in React Native's ScrollView

Jamgreen picture Jamgreen · Sep 25, 2017 · Viewed 15.6k times · Source

I am trying to make my content start 100 px from the top in React Native. I have tried with

const OFFSET = 100
const ScrollViewTest = (props) => (
  <ScrollView
    contentInset={{ top: OFFSET }}
    contentOffset={{ y: OFFSET }}
  >
    <Text>Test</Text>
  </ScrollView>
)

But when I render the screen, it starts from 0 px, but if I scroll a little, it will scroll to 100px from the top and stay there.

So it seems React Native doen't trigger the contentOffset and contentInset properties on initialization.

How can I fix this? I have also tried setting automaticallyAdjustContentInsets={false} with no changes.

Also, it seems these properties are for iOS only. Are there any similar properties for Android?

Answer

Peter Theill picture Peter Theill · Jun 6, 2018

You should use the contentContainerStyle1 property with a marginTop on your ScrollView.

By using this property it will apply the container wrapping your children (which I believe is what you want in this case) and with the additional benefit of working on both iOS and Android.

I.e.

const OFFSET = 100
const ScrollViewTest = (props) => (
  <ScrollView
    contentContainerStyle={{ marginTop: OFFSET }}
  >
    <Text>Test</Text>
  </ScrollView>
)