How to scroll to bottom in react?

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

    I just want to update the answer to match the new React.createRef() method, but it's basically the same, just have in mind the current property in the created ref:

    class Messages extends React.Component {
    
      const messagesEndRef = React.createRef()
    
      componentDidMount () {
        this.scrollToBottom()
      }
      componentDidUpdate () {
        this.scrollToBottom()
      }
      scrollToBottom = () => {
        this.messagesEnd.current.scrollIntoView({ behavior: 'smooth' })
      }
      render () {
        const { messages } = this.props
        return (
          
    {messages.map(message => )}
    ) } }

    UPDATE:

    Now that hooks are available, I'm updating the answer to add the use of the useRef and useEffect hooks, the real thing doing the magic (React refs and scrollIntoView DOM method) remains the same:

    import React, { useEffect, useRef } from 'react'
    
    const Messages = ({ messages }) => {
    
      const messagesEndRef = useRef(null)
    
      const scrollToBottom = () => {
        messagesEndRef.current.scrollIntoView({ behavior: "smooth" })
      }
    
      useEffect(scrollToBottom, [messages]);
    
      return (
        
    {messages.map(message => )}
    ) }

    Also made a (very basic) codesandbox if you wanna check the behaviour https://codesandbox.io/s/scrolltobottomexample-f90lz

提交回复
热议问题