Sometimes websites are overloaded with text, images, and other forms of
content. The only way to fit all of this information on a screen is to allow
scrolling.
In this article, we will show you how to implement a scroll to
bottom feature in React, which is useful for scrolling long lists, tables, or
long content.
One way is to create a button that takes users to the bottom when clicked. Alternatively, you can implement scroll to bottom as soon as web application loads.
Let’s start with a button.
Abutton that scrolls to bottom in React
Let’s start with a simple example. A scrollable container with a header text and one button. Clicking this button will take you to the bottom of the scrollable container.
The scrollIntoView() is the native method available on the Element interface. When called on an element, it makes the element visible to the user. If you have a long scrollable container, you can call the scrollIntoView() method on <div> element to display its bottom end.
React components are usually written in JSX. If that’s the case, react scroll to bottom feature is easy to set up.
Simply create a button element and set its onClick event handler to call scrollIntoView() method on the main container. Use arguments to specify which part of the element (in this case, end / bottom) you want the user to see.
Let’s look at a code example:
import "./styles.css";
import { useRef } from "react";
export default function App() {
const div = useRef(null);
return (
<div className="App" ref={div}>
<h1>Welcome to web application</h1>
<button
onClick={() =>
div.current.scrollIntoView({ behavior: "smooth", block: "end" })
}
>
Scroll to bottom
</button>
</div>
);
}
Here is the GIF that shows how the code works. You can also go to CodeSandbox to check out a live demo.
Full article on SimpleFrontEnd