bleepmeh
bleepmeh

Reputation: 1037

How do I make Scrollview auto scroll when the content size changes in React Native

I currently have a vertical ScrollView that has many expandable cards inside. When one of the cards expands, its height will increase by Y, and therefore the ScrollView content size's height will increase by Y.

I want to make the ScrollView automatically scroll by Y when the content size increases, and scroll by -Y when the content size decreases. How should I achieve this?

Upvotes: 1

Views: 2016

Answers (1)

Jay
Jay

Reputation: 919

You can use "onContentSizeChange", this will return new height after change your view. It's work for me.

<ScrollView
      ref={scrollView => {
        this.scrollView = scrollView;
      }}
      onContentSizeChange={(contentWidth, contentHeight) => {
        console.log('contentHeight :==> \n', contentHeight);
        this.scrollView.scrollTo({
          x: 0,
          y: contentHeight + YOUR_VIEW_HEIGHT - SCREEN_HEIGTH,
          animated: true,
        });
      }}
    >

...

YOUR_VIEW_HEIGHT will get from View's onLayout method.

Upvotes: 3

Related Questions