Skip to content

Instantly share code, notes, and snippets.

@altavir
Last active September 28, 2019 09:06
Show Gist options
  • Save altavir/188dc54d28e86ae87b45eb2511bf904a to your computer and use it in GitHub Desktop.
Save altavir/188dc54d28e86ae87b45eb2511bf904a to your computer and use it in GitHub Desktop.
A demonstration of use external state changer for react with kotlin-js.
package ru.mipt.npm.demo.react
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.html.dom.append
import kotlinx.html.js.*
import react.*
import react.dom.div
import react.dom.h1
import react.dom.p
import react.dom.render
import kotlin.browser.document
import kotlin.browser.window
typealias Change = State.() -> Unit
interface Properties : RProps {
var value: String
var changes: ReceiveChannel<Change>
}
interface State : RState {
var value: String
}
class Component(props: Properties) : RComponent<Properties, State>(props) {
init {
//starting accepting change events for internal state
GlobalScope.launch {
for (change in [email protected]) {
setState(change)
}
}
}
override fun State.init(props: Properties) {
value = props.value
}
override fun RBuilder.render() {
div {
p {+"Hello ${state.value}!"}
}
}
}
fun main() {
window.onload = {
val channel = Channel<Change>(capacity = Channel.RENDEZVOUS)
render(document.getElementById("app")) {
h1 {+"React content"}
val element = child(Component::class) {
attrs {
value = "react"
changes = channel
}
}
}
document.getElementById("static")?.append {
h1 { +"Static content" }
button {
a {+"Change"}
onClickFunction = {
GlobalScope.launch(Dispatchers.Main) {
var counter = 0
while (isActive) {
delay(500)
channel.send {
value = "react_${counter++}"
}
}
}
}
}
}
}
}
<!DOCTYPE html>
<html lang="US">
<head>
<meta charset="utf-8">
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">-->
<title>React demo</title>
<script type="text/javascript" src="main.bundle.js"></script>
</head>
<body class="testApp">
<div id="app"></div>
<div id="static"></div>
</body>
</html>
repositories {
mavenCentral()
maven("https://kotlin.bintray.com/kotlin-js-wrappers/")
}
kotlin {
target {
useCommonJs()
browser()
}
sourceSets["main"].dependencies {
implementation(kotlin("stdlib-js"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-js:1.3.2")
implementation("org.jetbrains:kotlin-react-dom:16.9.0-pre.83-kotlin-1.3.50")
implementation(npm("react","16.9.0"))
implementation(npm("react-dom","16.9.0"))
implementation(npm("core-js"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment