본문 바로가기

React + React Native + Expo

[React Native] 채팅창 스크롤 뷰 아래에 위치하도록 만들기 kepping a ScrollView scrolled to the bottom

반응형

  React Native Expo 채팅장 스크롤 뷰 아래에 고정시키기   

React Native Expo 로 chatting 구현을 매 채팅이 보내질 때마다 rerender 를 했다.

채팅이 많아지니 render 할 때마다 계속 위 (가장 처음 메세지) 로 올라간다 

 

처음에는 style 로 옮겨보려다가 실패 !  stackOverFlow에서 찾은 방법은 useRef 를 사용해서 ScrollView에다가 아래의 옵션값을 설정해 주었다. 

ref={scrollViewRef}
onContentSizeChange={()=>scrollViewRef.current.scrollToEnd({animated:true})}>

 

=> 이렇게 하니까 채팅을 계속 써내려가도 screen이 위로 올라가지않고 맨 아래 (가장 최근에 보낸 메세지가 보이도록) 에 고정이 되었따! 

 

전체 코드 

import React, { useLayoutEffect, useState, useEffect, useRef } from 'react'    // 1) useRef 추가  
import {
    StyleSheet, Text, View, Platform, KeyboardAvoidingView,
    TouchableOpacity, StatusBar, SafeAreaView, ScrollView, TextInput,
    Keyboard, TouchableWithoutFeedback,
} from 'react-native'
.
.
.
                <TouchableWithoutFeedback onPress={Keyboard.dismiss} >
                    <>
                        <ScrollView 
                            contentContainerStyle={{ paddingTop: 15, paddingBottom:10, }} 
                            
                            //    2) 아래 코드 2 줄 추가 
                            
                            ref={scrollViewRef} 
                            onContentSizeChange={()=>scrollViewRef.current.scrollToEnd({animated:true})}>
                        
                            {/* 채팅들이 기록되는 곳 by 세연 */}
                            {messages.map((data, i) =>
                                data.user_email === user_email ?
                                    (
                                        <View key={i} >
                                            <View style={styles.reciever}>
                                                <Avatar
                                                    position="absolute"
                                                    rounded
                                                    bottom={-15}
                                                    right={-13}
                                                    size={30}
 .
 .
 .

 

 

References : https://stackoverflow.com/questions/29310553/is-it-possible-to-keep-a-scrollview-scrolled-to-the-bottom

 

Is it possible to keep a ScrollView scrolled to the bottom?

For a chat-like app, I want to keep a ScrollView component scrolled to the bottom, because newest messages appear under the older ones. Can we adjust the scroll position of a ScrollView?

stackoverflow.com

 

반응형