How do I scroll a scrollable element to the bottom...
# compose-web
e
How do I scroll a scrollable element to the bottom from Kotlin/jb-compose code? Use case: I have an element that can grow in vertical size (child elements are added to the bottom), and that has a max height, and on overflow it scrolls, e.g.:
Copy code
Div(attrs = {
    style {
        maxHeight(8.em)
        overflow("scroll")
    }
}) { /* content */ }
When the content overflows, I'd like the scrollable element to scroll to the bottom (by default it stays at the current scroll position, which is the top if never scrolled). I've found solutions in JS that probably work, but I'd like to know if this can be done nicely from my Kotlin code.
b
Nope, nothing special in kotlin for it. Just replicate usual js solutions
e
So I guess I add an ID, get the element by ID, and scroll it
b
You can get access to dom element via nativeElement property inside DisposableSideEffect or atts.ref lambdas
e
Hmm, never did that before. Let me try that out
So you mean something like the following?
Copy code
Div(attrs = {
    style {
        maxHeight(8.em)
        overflow("scroll")
    }
    ref {
        it.scrollTop = it.scrollHeight.toDouble()
        onDispose {  }
    }
}) {}
(
it
is a
HTMLDivElement
here)
That doesn't work, because I think the style is applied before the height changes, when adding the child elements
Side note: It's nice that
ref {}
provides the native element, but it's not very nice that you must call
onDispose {}
b
Either that or inside DisposableSideEffect. There used to be DomSideEffect which did not demand onDispose, but that's now deprecated
So use DisposableSideEffect which is invoked whenever any of its dependencies change
e
It works now, like you said, with a ref disposable effect or explicit disposable effect
Thanks
e
I did have to scroll to a large value, e.g.
99999.9
(not nice that it must be a double instead of any number)
It confused me too 😛
About https://kotlinlang.slack.com/archives/C01F2HV7868/p1664097409524329?thread_ts=1664028694.891579&cid=C01F2HV7868 Using the
ref
approachs in the attrs doesn't work, because that disposable effect only runs once when the composition enters for the first time. I want to run on every recomposition, so I ended up using a disposable effect in the
Div {}
block
b
Yea, as it should. That's why you have two kinds of ref effects