How to fix React Native ScrollView default at bottom

Viewed 329

I'm trying to build a Chat App with React Native.

In the chat screen, there is a ScrollView for every message sent and received.

However, every time when I leave the screen and back in, the default of the ScrollView is at the top. I've written a function to scrollToEnd after rendered, but that is After Rendered, I need to set the ScrollView at the bottom before it actually shows.

I've tried (but users can see it scrolling as soon as it is rendered):

const scrollToBottom = () => {
    scrollEl.current.scrollIntoView({ behavior: 'smooth'})
}

useEffect(() => {
    scrollToBottom()
}, [scrollEl, loading, chatHistory])

return(
    <ScrollView bottom={0} w="100%" bg="blueGray.100" inverted>
        <VStack flex={1} w="100%" id="VStack">
            {!loading && chatHistory.chats[roomId] && chatHistory.chats[roomId].length > 0 && chatHistory.chats[roomId].map((chat, index) =>
                <ChatItem type={chat.type}
                    text={chat.text}
                    fromSelf={chat.fromSelf}
                    key={index}
                />
            )}
            <Box ref={scrollEl} />
        </VStack>                
    </ScrollView>
)

I've tried:

  • Set scale: -1 at CSS, which actually invert the whole screen upside down.
  • Thus, I have to invert every single message to invert them back to the normal side.
  • Meanwhile, the scrolling is totally in the opposite way when you scroll by mouse or slide on the screen.

Any solutions or suggestions?

Thanks!

1 Answers
Related