You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

2.3 KiB

Events handling in Compose Web

You can add event listeners in the attrs block:

onClick

Button(
    attrs = {
        onClick { event -> 
            // event is of `SyntheticMouseEvent` type    
            println("button clicked at ${event.movementX}, ${event.movementY}")
            
            val nativeEvent = event.nativeEvent // [MouseEvent](https://developer.mozilla.org/en/docs/Web/API/MouseEvent)
        }
    }
) {
    Text("Button")
}

onInput

val text = remember { mutableStateOf("") }

TextArea(
    value = text.value,
    attrs = {
        onInput {
            text.value = it.value
        }
    }
)

Other event handlers

For events that don't have their own configuration functions in the attrs block, you can use addEventListener with the name of the event, options, and an pass an eventListener which receives a SyntheticEvent. In this example, we're defining the behavior of a Form element when it triggers the submit event:

Form(attrs = {
    this.addEventListener("submit") {
        console.log("Hello, Submit!")
        it.preventDefault()
    }
})

There are more event listeners supported out of a box. We plan to add the documentation for them later on. In the meantime, you can find all supported event listeners in the source code.

Runnable example

import androidx.compose.runtime.*
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
import org.jetbrains.compose.web.renderComposable

fun main() {
    renderComposable(rootElementId = "root") {
        Button(
            attrs = {
                onClick { event ->
                    println("button clicked at ${event.movementX}, ${event.movementY}")
                }
            }
        ) {
            Text("Button")
        }

        val text = remember { mutableStateOf("") }

        TextArea(
            value = text.value,
            attrs = {
                onInput {
                    text.value = it.value
                }
            }
        )

        Span {
            Text("Typed text = ${text.value}")
        }
    }
}