How to scroll to bottom in react?

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

    The easiest and best way I would recommend is.

    My ReactJS version: 16.12.0


    For Class Components

    HTML structure inside render() function

        render()
            return(
                
                    
    Message 1
    Message 2
    Message 3
    ) )

    scrollToBottom() function which will get reference of the element. and scroll according to scrollIntoView() function.

      scrollToBottom = () => {
        const { messageList } = this.refs;
        messageList.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
      }
    

    and call the above function inside componentDidMount() and componentDidUpdate()


    For Functional Components (Hooks)

    Import useRef() and useEffect()

    import { useEffect, useRef } from 'react'
    

    Inside your export function, (same as calling a useState())

    const messageRef = useRef();
    

    And let's assume you have to scroll when page load,

    useEffect(() => {
        if (messageRef.current) {
          messageRef.current.scrollIntoView(
            {
              behavior: 'smooth',
              block: 'end',
              inline: 'nearest'
            })
        }
      })
    

    OR if you want it to trigger once an action performed,

    useEffect(() => {
      if (messageRef.current) {
        messageRef.current.scrollIntoView(
          {
            behavior: 'smooth',
            block: 'end',
            inline: 'nearest'
          })
      }
    },
    [stateVariable])
    

    And Finally, to your HTML structure

    return(
        
            
    // <= The only different is we are calling a variable here
    Message 1
    Message 2
    Message 3
    )

    for more explanation about Element.scrollIntoView() visit developer.mozilla.org

    More detailed explanation in Callback refs visit reactjs.org

提交回复
热议问题