Auto scroll to bottom of React div

I use chrome dev tools when needed but also like old school printf debug so I’m working on a template with a Debug component (still in progress).

I add debug messages to an array and render it by writing each element to a <p> tag (in writeBuffer) which is wrapped in a div with class name writebuffer; the css has overflow-y: scroll so I can scroll back and forth as needed. This also means I can copy all messages from the Debug window; I also implemented a simple print as well.

The problem I am trying to solve is that I want the div to auto scroll to the bottom on each render, to get an effect like tail -f so I always see the last output. Note I also want to keep the debug controls (buttons) on the left.

Can anyone help please?

Oops - forget to link the pen: Debug template

Welcome, there.

It should be as easy as using the .scrollTop property: Element.scrollTop - Web APIs | MDN (

It is quite common.

I would try something like this:

writeBuffer() {
    try {
    const buffer = document.getElementById("printBuffer");
    buffer.scrollTop = buffer.scrollHeight;
    } catch (err) {
    return (
        {, i) => (
          <p key={i}>{m}</p>

The thing is, the height is not exact. So, you will need to tweak around the values.

Also, it is not ideal that it is within a try...catch like that. I just did that for ease of testing, but you can change it.

A better idea would be to find a way to get the .scrollTop to be set after returning.

Hope this helps

@Sky020 , thanks very much for that - it got me in the right direction.

The solution I came up with is good enough to handle ~50,000 lines without much performance hit - good enough for me.

I updated the pen (but still in progress): Debug template.