How to scroll to bottom in react?

前端 未结 19 881
执笔经年
执笔经年 2020-11-28 18:27

I want to build a chat system and automatically scroll to the bottom when entering the window and when new messages come in. How do you automatically scroll to the bottom of

19条回答
  •  温柔的废话
    2020-11-28 18:55

    react-scrollable-feed automatically scrolls down to the latest element if the user was already at the bottom of the scrollable section. Otherwise, it will leave the user at the same position. I think this is pretty useful for chat components :)

    I think the other answers here will force scroll everytime no matter where the scrollbar was. The other issue with scrollIntoView is that it will scroll the whole page if your scrollable div was not in view.

    It can be used like this :

    import * as React from 'react'
    
    import ScrollableFeed from 'react-scrollable-feed'
    
    class App extends React.Component {
      render() {
        const messages = ['Item 1', 'Item 2'];
    
        return (
          
            {messages.map((message, i) => 
    {message}
    )}
    ); } }

    Just make sure to have a wrapper component with a specific height or max-height

    Disclaimer: I am the owner of the package

提交回复
热议问题