Shashika Virajh
Shashika Virajh

Reputation: 9457

React Native Scroll To Bottom

I want to scroll down a list to the bottom when I click on an input in react native.

This is my code.

render() {
    return (
      <View style={styles.container}>
        <View style={styles.commentListWrapper}>
          <ScrollView>
            <Animated.View>
              <PostProfileBar
                profile={this.state.post.author}
                timeAgo={this.state.post.timeAgo}
              />

              <ClickableImage
                source={{ uri: this.state.post.postImage }}
                height={height * (3 / 10)}
                width={width}
                onPress={() => alert("Image Clicked")}
              />
            </Animated.View>

            <CommentFlatList
              data={this.state.data}
              refreshing={this.state.refreshing}
            />
          </ScrollView>
        </View>

        <View
          style={[
            styles.commentInputWrapper,
            { flex: this.state.commentBoxFlex }
          ]}
        >
          <CommentInput
            iconName="upload"
            placeholder="Type Comment"
            isFocused={true}
            fontSize={this.state.comment.value.length > 0 ? 16 : 20}
            value={this.state.comment.value}
            multiline={true}
            onChangeText={value => this.onChangeComment(value)}
            onPress={() => this.uploadComment()}
            invalidInput={styles.invalidInput}
            valid={this.state.comment.valid}
            touched={this.state.comment.touched}
            disabled={!this.state.comment.valid}
          />
        </View>
      </View>
    );
  }

Now, when I click on the commentinput, I want to scroll down the list to the bottom. How can I achieve this?

Upvotes: 10

Views: 12844

Answers (2)

Simon
Simon

Reputation: 6462

In 2020 with the new hooks API, the new way to do it is: Create a reference:

const scrollViewRef = useRef();

Associate it to the scroll view:

<ScrollView ref={scrollViewRef}>

And then call it with:

 scrollViewRef.current.scrollToEnd({animated: true})

Upvotes: 19

Roy Wang
Roy Wang

Reputation: 11260

You can get a ref on the ScrollView:

<ScrollView
  ref={(view) => {
    this.scrollView = view;
  }}
>

Then call scrollToEnd in the onPress method of <CommentInput>:

onPress={() => {
  this.scrollView.scrollToEnd({ animated: true }); 
  this.uploadComment(); 
}}

Upvotes: 15

Related Questions