Yash Vaghela
Yash Vaghela

Reputation: 612

Auto scroll in ScrollView react-native

I am creating chat app and want to auto scroll to bottom automatically in ScrollView every time a new message received.

Here is my code:

<ScrollView>
  <FlatList
    data={this.state.dataSource}
    renderItem={({ item }) => <SenderChatRow data={item} />}
    keyExtractor={(item, index) => index}
  />
  {this._bookingRequestMessage()}
</ScrollView>

Upvotes: 4

Views: 17775

Answers (3)

Manish Singh Chouhan
Manish Singh Chouhan

Reputation: 381

I was trying to doing the same like scrolling the screen in click of a button.

const [offset,setOffset] = useState(0);
        const scrollViewRef = useRef();
    
    const scrollDown = () => {
        const y = offset + 101;  /// we can get the height from the onLayout in view
        scrollViewRef.current.scrollTo({x: 0, y, animated: true});
        setOffset(y);
    }
    
    return (
        <ScrollView ref={scrollViewRef} >
            <Button onPress={scrollDown} title="Scroll down" />
            <Text>
                  [ Very long text here where user has to scroll ]
            </Text>
        </ScrollView>
    )

Upvotes: 1

chetan godiya
chetan godiya

Reputation: 316

for scrollview add this lines into your scrollview

<ScrollView
            ref={(ref) => this.flatListRef = ref}
            contentContainerStyle={{ flex: 1 }}
            onContentSizeChange={(width, height) => this.flatListRef.scrollToEnd({ animated: false })}
          >

and then import Keyboard from react-native add then add this code into your script

componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
}
}

 componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }
  
  _keyboardDidShow() {
    this.scrollView.scrollToEnd({ animated: false })
  }

Upvotes: 0

MoKhajavi75
MoKhajavi75

Reputation: 2702

From React Native 0.41 and later you can use this:

<ScrollView
    ref={ref => this.scrollView = ref}
    onContentSizeChange={(contentWidth, contentHeight)=>{        
        this.scrollView.scrollToEnd({animated: true});
    }}>
</ScrollView>

Take a look at Docs

Update

As you mentioned you have problem when the keyboard is open, first:

import { Keyboard } from "react-native";

Then use componentDidMount():

componentDidMount() {
  this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', 
    this._keyboardDidShow.bind(this));
}


componentWillUnmount() {
  this.keyboardDidShowListener.remove();
  this.keyboardDidHideListener.remove();
}

_keyboardDidShow() {
  this.scrollView.scrollToEnd({ animated: false })
}

Thanks chetan godiya for the update!

Upvotes: 13

Related Questions