React Native ScrollView Component

30 Jun, 2021
The ScrollView Component is an inbuilt react-native component that serves as a generic scrollable container, with the ability to scroll child components and views inside it. It provides the scroll functionality in both directions- vertical and horizontal (Default: vertical). It is essential to provide the ScrollView Component with a bounded height since they contain unbounded-height children into a bounded container.
Advantage of using ScrollView Component: The most popular use of the ScrollView Component is to display a few items of a limited size. All the child components (text, views, images, etc.) of a ScrollView Component are rendered, even if they are not currently visible on the screen. 
Disadvantage of using ScrollView Component: The major drawback of using the ScrollView Component is its performance issues. Since the ScrollView component renders all its children components at once, it results in slow rendering and increased memory usage.
Props in ScrollView:
StickyHeaderComponent: Component used to render sticky headers. If not provided, the default ScrollViewStickyHeader component will be used.
alwaysBounceHorizontal: If true, the ScrollView bounces horizontally when it reaches the end irrespective of whether the content is smaller than the ScrollView itself.
alwaysBounceVertical: If true, the ScrollView bounces vertically when it reaches the end irrespective of whether the content is smaller than the ScrollView itself.
automaticallyAdjustContentInsets: Controls whether iOS should automatically adjust the content inset for scroll views that are placed behind a navigation bar or tab bar/toolbar.
bounces: If true, the ScrollView bounces when it reaches the end of the content only when the content is larger than the ScrollView along the axis of the scroll direction.
bouncesZoom: If true, gestures can drive zoom past min/max and the zoom will animate to the min/max value at gesture ends.
canCancelContentTouches: If false, once tracking starts, won’t try to drag if the touch moves.
centerContent: If true, the ScrollView automatically centers the content when the content is smaller than the scroll view bounds.
contentContainerStyle: These styles will be applied to the scroll view content container which wraps all the child views.
contentInset: Specifies the amount by which the ScrollView content is inset from the edges of the ScrollView.
contentInsetAdjustmentBehavior: It is used to specifies how the safe area insets are used to modify the content area of the ScrollView.
contentOffset: Manually sets the starting scroll offset.
decelerationRate: A floating-point number that determines how quickly the scroll view decelerates after the user lifts their finger.
directionalLockEnabled: The ScrollView will try to lock to only vertical or horizontal scrolling while dragging if this is set to true.
disableIntervalMomentum: The ScrollView stops on the next index if this is set to true.
disableScrollViewPanResponder: If true, the default JS pan responder on the ScrollView is disabled, and full control over touches inside the ScrollView is left to its child components.
endFillColor: Sometimes a scrollview takes up more space than its content fills.
fadingEdgeLength: Fades out the edges of the scrolling content.
horizontal: If true, then scroll view’s children are arranged horizontally in a row instead of vertically in a column.
indicatorStyle: The style of the scroll indicators.
invertStickyHeaders: This is usually used with inverted ScrollViews. If sticky headers should stick at the bottom instead of the top of the ScrollView. 
keyboardDismissMode: It is used to determine whether the keyboard gets dismissed in response to a drag.
keyboardShouldPersistTaps: It is used to determine when the keyboard should stay visible after a tap.
maintainVisibleContentPosition: The scroll view will adjust the scroll position so that the first child that is currently visible and at or beyond minIndexForVisible will not change position if this is set to true.
maximumZoomScale: It is used to denote the maximum allowed zoom scale.
minimumZoomScale: It is used to denote the minimum allowed zoom scale.
nestedScrollEnabled: Enables nested scrolling for Android API level 21+.
onContentSizeChange: It is a callback function that is called when the scrollable content view of the ScrollView changes.
onMomentumScrollBegin: It is a callback function that is called when the momentum scroll starts.
onMomentumScrollEnd: It is a callback function that is called when the momentum scroll ends.
onScroll: Fires at most once per frame during scrolling.
onScrollBeginDrag: It is a callback function that is called when the user begins to drag the scroll view.
onScrollEndDrag: It is a callback function that is called when the user stops dragging the scroll view and it either stops or begins to glide.
onScrollToTop: Fires when the scroll view scrolls to the top after the status bar has been tapped.
overScrollMode: It is used to override the default value of overScroll mode.
pagingEnabled: This can be used for horizontal pagination. If this is set to true, then the scroll view stops on multiples of the scroll view’s size when scrolling. 
persistentScrollbar: Causes the scrollbars not to turn transparent when they are not in use.
pinchGestureEnabled: If true, ScrollView allows the use of pinch gestures to zoom in and out.
refreshControl: A RefreshControl component used to provide pull-to-refresh functionality for the ScrollView. 
scrollEnabled: If false, the view cannot be scrolled via touch interaction.
scrollEventThrottle: This controls how often the scroll event will be fired while scrolling.
scrollIndicatorInsets: The amount by which the scroll view indicators are inset from the edges of the scroll view.
scrollPerfTag: It is the tag used to log scroll performance on this scroll view. 
scrollToOverflowEnabled: If true, then scroll view can be programmatically scrolled beyond its content size.
scrollsToTop: If true, then scroll view scrolls to the top when the status bar is tapped.
showsHorizontalScrollIndicator: If true, shows a horizontal scroll indicator.
showsVerticalScrollIndicator: If true, shows a vertical scroll indicator.
snapToAlignment: The snapToAlignment will define the relationship of the snapping to the scroll view when snapToInterval is set to true.
snapToEnd: It is used in conjunction with snapToOffsets. The end of the list counts as a snap offset by default.
snapToInterval: If set, causes the scroll view to stop at multiples of the value of snapToInterval.
snapToOffsets: If set, causes the scroll view to stop at the defined offsets.
snapToStart: It is used in conjunction with snapToOffsets. The beginning of the list counts as a snap offset by default.
stickyHeaderIndices: An array of child indices determining which children get docked to the top of the screen when scrolling.
zoomScale: It is used to denote the current scale of the scroll view content.
 
Methods:
flashScrollIndicators(): This method is used to displays the scroll indicators momentarily.
scrollTo(): This method is used to Scrolls to a given x, y offset, either immediately, with a smooth animation.
scrollToEnd(): If this is vertical ScrollView scrolls to the bottom. If this is horizontal ScrollView scrolls to the right.
scrollWithoutAnimationTo(): Deprecated, use scrollTo instead.
Now let’s start with the implementation:
Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
Step 2: Now create a project by the following command.expo init myapp
Step 2: Now create a project by the following command.
expo init myapp
Step 3: Now go into your project folder i.e. myappcd myapp
Step 3: Now go into your project folder i.e. myapp
cd myapp
Project Structure: It will look like the following.
Example: Now let’s implement the ScrollView. In the following example, we have a scrollable list of all sample items.
App.js
import React, { Component } from "react";import { Text, Button, View, StyleSheet, ScrollView } from "react-native";  class App extends Component {  state = {    // Sample data    items: [      { item: "Item 1", price: "10", id: 1 },      { item: "Item 2", price: "20", id: 2 },      { item: "Item 3", price: "30", id: 3 },      { item: "Item 4", price: "40", id: 4 },      { item: "Item 5", price: "50", id: 5 },      { item: "Item 6", price: "60", id: 6 },      { item: "Item 7", price: "70", id: 7 },      { item: "Item 8", price: "80", id: 8 },      { item: "Item 9", price: "90", id: 9 },      { item: "Item 10", price: "100", id: 10 },      { item: "Item 11", price: "110", id: 11 },      { item: "Item 12", price: "120", id: 12 },      { item: "Item 13", price: "130", id: 13 },      { item: "Item 14", price: "140", id: 14 },      { item: "Item 15", price: "150", id: 15 },    ],  };  render() {    return (      <View style={styles.screen}>        <ScrollView> // use of ScrollView Component          {this.state.items.map((item, index) => (            <View key={item.id}>              <View style={styles.summary}>                <Text style={styles.summaryText}>                  {item.item} <Text style={styles.amount}>                      ${item.price}</Text>                </Text>                <Button title="Order" color="#FFC107"                       onPress={() => { }} />              </View>            </View>          ))}        </ScrollView>      </View>    );  }}  // Screen stylesconst styles = StyleSheet.create({  screen: {    margin: 20,  },  summary: {    flexDirection: "row",    alignItems: "center",    justifyContent: "space-between",    marginBottom: 20,    padding: 10,    shadowColor: "black",    shadowOpacity: 0.26,    shadowOffset: { width: 0, height: 2 },    shadowRadius: 8,    elevation: 5,    borderRadius: 10,    backgroundColor: "white",  },  summaryText: {    fontFamily: "openSansBold",    fontSize: 18,  },  amount: {    color: "#C2185B",  },});  export default App;
Start the server by using the following command.
npm run android
Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. We will be able to see the scrollable list of all items (dummy data) as shown below.
Reference: https://reactnative.dev/docs/scrollview
Picked
React-Native
React-Native Component
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.