reactjsautoscroll

Auto-scroll in div with React


Having a div with dynamic logs content (props.logs), How can I auto scroll to the bottom?

  <div className='rc_logsContent' ref={logsRef}>
    <Collapse isOpened={isOpened} >
       <p
         dangerouslySetInnerHTML={{__html: formatNote(props.logs)}}
       />
    </Collapse>
  </div> 

Solution

  • The problem is you are passing the ref to the div element in which your component is rendered. I would suggest you use a dummy div at the end of your content and then scroll to that whenever your component is updated. Just check with this modified code.

    <div className="rc_logsContent">
      <Collapse isOpened={isOpened}>
        <p dangerouslySetInnerHTML={{ __html: formatNote(props.logs) }} />
        <div ref={logsRef} />
      </Collapse>
    </div>;
    
    

    Attaching a sandbox with the same scroll functionality. You can check and modify based on your requirements.

    Edit scrollToBottomExample (forked)