react native scrollview scrollto()

React Native ScrollView scrollTo() function

If you are building a mobile application using React Native, chances are you will need to implement a ScrollView at some point. The ScrollView component provides a scrolling view of its contents, which can be vertically or horizontally oriented. In addition to scrolling automatically, the ScrollView component also provides the ability to scroll programmatically using the scrollTo() function.

How to use scrollTo()

The scrollTo() function is used to programmatically scroll the ScrollView to a specific position. You can call this function on a ref to the ScrollView component. The function takes two arguments: x and y, which represent the horizontal and vertical positions to scroll to, respectively.


import React, { Component } from 'react';
import { ScrollView } from 'react-native';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.scrollViewRef = React.createRef();
  }

  scrollToTop = () => {
    this.scrollViewRef.current.scrollTo({ x: 0, y: 0, animated: true });
  };

  render() {
    return (
      <ScrollView ref={this.scrollViewRef}>
        // content here
      </ScrollView>
    );
  }
}

In this example, we create a ref to the ScrollView component using the React.createRef() method. We then define a scrollToTop() function which calls the scrollTo() function on the ref with x = 0 and y = 0. This will scroll the ScrollView to the top of its contents. We attach the ref to the ScrollView component using the ref prop.

Other ways to use scrollTo()

In addition to specifying an x and y position, the scrollTo() function also accepts an options object with the following properties:

  • animated: If true, the ScrollView will scroll to the specified position with an animation.
  • duration: The duration of the animation in milliseconds.
  • useNativeDriver: If true, use the native driver for the animation.

For example:


scrollToTop = () => {
  this.scrollViewRef.current.scrollTo({
    x: 0,
    y: 0,
    animated: true,
    duration: 500,
    useNativeDriver: true
  });
};

This will scroll the ScrollView to the top with an animation. The animation duration will be 500 milliseconds, and the native driver will be used if available.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe