DEV Community

Victoria
Victoria

Posted on

Anchor scroll at the bottom of the container with dynamic content

This article serves as a short tutorial where I'll show you how to easily implement a somewhat tricky functionality.

The case in question is a basic message box, where the latest content should appear at the bottom of the container, with the scroll anchored there.

Here is our problem:

Problem

Approach 1 - CSS only

The simplest solution is to use a reversed flex column, which will cause the scroll to stick to the bottom:

Image description

Implementation in CSS:

  1. Set the display of the container to flex.
  2. Use flex-direction: column-reverse; to start filling content from the bottom.
  3. Ensure your container has a set height and overflow: auto; to enable scrolling.

Approach 2 - Adding some JavaScript

For automatic scrolling upon the addition of new content, you can tweak the smoothness to create the best user experience:

Image description

Implementation in React:

  1. Use the useRef hook to maintain a reference to the container.
  2. Use the useEffect hook to detect changes in the content of the container.
  3. When new content is added, use the scrollIntoView method or adjust the scrollTop property to scroll to the bottom of the container.

Add the following code:



const containerRef = useRef(null);

useEffect(() => {
const element = containerRef.current;
if (element) {
element.scrollTop = element.scrollHeight;
}
}, [messages]); // assuming 'messages' is the state holding the chat content

Enter fullscreen mode Exit fullscreen mode




Conclusion:

Now you know two of the simplest ways to achieve a bottom-anchored scroll with dynamic content. If you have other methods or suggestions, please feel free to share them with me!

You can also combine the two approaches mentioned and experiment with the smoothness of the scroll. You can find an example app here.

Happy coding and see you soon!
Image description

Top comments (0)