Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

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

    Spencer CarliSpencer Carli

    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.

    react-nativeReact Native
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    Instructor: 00:00 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.

    00:20 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.

    00:36 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.

    00:51 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.

    01:20 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.

    Discuss

    Discuss