How to scroll to bottom in react?

前端 未结 19 782
执笔经年
执笔经年 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:51

    Working Example:

    You can use the DOM scrollIntoView method to make a component visible in the view.

    For this, while rendering the component just give a reference ID for the DOM element using ref attribute. Then use the method scrollIntoView on componentDidMount life cycle. I am just putting a working sample code for this solution. The following is a component rendering each time a message received. You should write code/methods for rendering this component.

    class ChatMessage extends Component {
        scrollToBottom = (ref) => {
            this.refs[ref].scrollIntoView({ behavior: "smooth" });
        }
    
        componentDidMount() {
            this.scrollToBottom(this.props.message.MessageId);
        }
    
        render() {
            return(
                
    Message content here...
    ); } }

    Here this.props.message.MessageId is the unique ID of the particular chat message passed as props

提交回复
热议问题