How to scroll to the bottom of JSX elements in React

#react

Last updated on Nov 25, 2020 by Suraj Sharma



In this tutorial, you will learn how you can scroll to the bottom of a JSX element in React using useRef() hook


Consider, you have a function component <ListItems /> and you want to scroll to the bottom of the ListItems component on click of a button


import React from 'react';

const ListItems = (props) => {
  const handleClick= () => {}

  return (
    <>
      <div
        style={{ overflow: auto, height: 480 }}
        ref={divRef}
      >
        {props.children}
      </div>
      <button onClick={handleClick}>Scroll</button>
    </>
  );
}


Using useRef() hook


Now, we are going to define a divRef using useRef(null), which defines the divRef and initializes the divRef.current property to null


Next pass the divRef to the div’s ref property


import React from 'react';

const ListItems = (props) => {
  const divRef = React.useRef(null);

  const handleClick= () => {}

  return (
    <>
      <div
        style={{ overflow: auto, height: 480 }}
        ref={divRef}
      >
        {props.children}
      </div>
      <button onClick={handleClick}>Scroll</button>
    </>
  );
}


The handleClick event handler contains the logic to scroll to the bottom of the element, using scrollTop and scrollHeight


const handleClick = () => {
  // using scrollTop and scrollHeight
  divRef.current.scrollTop = divRef.current.scrollHeight
}


Or you can use the scrollIntoView() method to scroll to the bottom with a smooth transition


const handleClick = () => {
  // using scrollIntoView
  divRef.current.scrollIntoView({
    behavior: 'smooth'
  })
}


Related Solutions



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.