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

Spencer Carli
InstructorSpencer Carli
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

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.

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.

egghead
egghead
~ 29 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today