How to scroll to bottom in react?

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

    Do not use findDOMNode

    Class components with ref

    class MyComponent extends Component {
      componentDidMount() {
        this.scrollToBottom();
      }
    
      componentDidUpdate() {
        this.scrollToBottom();
      }
    
      scrollToBottom() {
        this.el.scrollIntoView({ behavior: 'smooth' });
      }
    
      render() {
        return 
    { this.el = el; }} /> } }

    Function components with hooks:

    import React, { useRef, useEffect } from 'react';
    
    const MyComponent = () => {
      const divRref = useRef(null);
    
      useEffect(() => {
        divRef.current.scrollIntoView({ behavior: 'smooth' });
      });
    
      return 
    ; }

提交回复
热议问题