Search code examples
reactjskotlinkotlin-multiplatformkotlin-js

Check if an image is loaded with Kotlin/JS for React


In my application (Kotlin/JS, React), the image is loaded from remote resource:

import org.w3c.dom.HTMLElement
import react.RBuilder
...
private var imageForLoad: HTMLElement? = null
...
override fun RBuilder.render() {
    styledDiv {
        css { +Style.div }
        styledImg {
            css { +Style.img }
            ref { imageForLoad = it as? HTMLElement }
        }
    }
    ...
    imageForLoad?.setAttribute("src", remoteResourceURL)
    // how to determine here if an image has already been loaded from a remote source?
}

How can I determine if an image has already loaded and displayed in the browser? I looked similar questions in the JavaScript section, but didn't find how to apply them when using Kotlin/JS.

Thanks for any comment/answer!


Solution

  • I found this solution:

    import kotlinx.html.js.onLoadFunction
    ...
    styledImg {
        css { +Style.img }
        ref { imageForLoad = it as? HTMLElement }
        attrs {
            onLoadFunction = { // invoked when the image has loaded 
                ...         
            }
        }
    }
    ...
    imageForLoad?.setAttribute("src", remoteResourceURL)