Enable Scroll in a React Native ScrollView Based on the Content Size

Author

Spencer Carli

Developer, cat dad, and devout pizza lover. Teaching at React Native School and building apps with Handlebar Labs.

Last Updated: April 26, 2018

Ever have the situation where you sometimes had content that was shorter than the screen size and didn’t require scrolling but occasionally had content taller than the screen size, thus necessitating scroll to allow the user to see all the content?

If that’s your case you can leverage the onContentSizeChange prop of a ScrollView and check whether the content height is taller than the screen size.

Here’s what I mean…

Container.js

// Get the screen height
const { height } = Dimensions.get('window');

export default class Container extends React.Component {
  state = {
    // We don't know the size of the content initially, and the probably won't instantly try to scroll, so set the initial content height to 0
    screenHeight: 0,
  };

  onContentSizeChange = (contentWidth, contentHeight) => {
    // Save the content height in state
    this.setState({ screenHeight: contentHeight });
  };

  render() {
    // Compare the content's height to the screen's height. If content's height > screen's height, enable scrolling
    const scrollEnabled = this.state.screenHeight > height;
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar barStyle="light-content" backgroundColor="#468189" />
        <ScrollView
          style={{ flex: 1 }}
          contentContainerStyle={styles.scrollview}
          scrollEnabled={scrollEnabled}
          onContentSizeChange={this.onContentSizeChange}
        >
          <View style={styles.content}>{this.props.children}</View>
        </ScrollView>
      </SafeAreaView>
    );
  }
}

Full Code: https://github.com/spencercarli/react-native-dynamic-scrollview

Here’s a video walkthrough as well

React Native School Logo

React Native School

Want to further level up as a React Native developer? Join React Native School! You'll get access to all of our classes and our private Slack community.