Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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

    react-nativeReact Native

    In this video, you will learn how to use onContentSizeChange to dynamically enable or disable the scrolling ability of a React Native ScrollView based on the height of the content inside of the ScrollView.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: To start off, our application is going to disable scrolling of the container when the content doesn't extend beyond the actual screen size. However, if we change the content to be something that does extend beyond the total screen size, we can see that the scroll is still enabled, but the content is cut off.

    To fix this, we'll go back to our container component. We're going to add a prop to our ScrollView. That is going to be onContentSizeChange. onContentSizeChange is going to be a function. We'll set it up to be this.onContentSizeChange, which we can go ahead and define.

    This onContentSizeChange function is going to take two arguments. The first one is going to be the contentWidth. The second one is going to be the contentHeight. With this, we're going to go ahead and say this.setState. We'll set screenHeight to be the contentHeight.

    Before we can use this, we'll go ahead and define some initial component state. Inside of here, we'll set the screenHeight to initially be 0To actually use this information, we're going to go ahead and import Dimensions from react-native. Then we can go ahead and pull the height off of Dimensions.get('window'). We can say this.state.screenHeight > height. When the screenHeight, when the content size is larger than the actual height of the screen, we'll go ahead and enable scroll.

    We can now see that we can scroll through the content when it extends beyond the size of the screen, but if we go back and use our smaller piece of content, scrolling is still disabled.