Skip to content

Instantly share code, notes, and snippets.

@loicdescotte

loicdescotte/App.scala

Last active Sep 3, 2019
Embed
What would you like to do?
Slinky React Hooks example
package hello.world
import slinky.web.html._
import slinky.core.facade.Hooks._
import slinky.core.FunctionalComponent
import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
@JSImport("resources/App.css", JSImport.Default)
@js.native
object AppCSS extends js.Object
@JSImport("resources/logo.svg", JSImport.Default)
@js.native
object ReactLogo extends js.Object
object App {
private val css = AppCSS
case class Props(name: String)
val component = FunctionalComponent[Props] { case Props(name) =>
val (state, updateState) = useState(0)
div(className := "App")(
header(className := "App-header")(
img(src := ReactLogo.asInstanceOf[String], className := "App-logo", alt := "logo"),
h1(className := "App-title")(s"Welcome to React (with Scala.js!), $name!")
),
p(className := "App-intro")(
"To get started, edit ", code("App.scala"), " and save to reload."
),
button(onClick := (_ => {
updateState(state + 1)
}))("Click me!"),
p(s"The button has been clicked $state times")
)
}
}
package hello.world
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExportTopLevel, JSImport}
import scala.scalajs.LinkingInfo
import slinky.core._
import slinky.web.ReactDOM
import slinky.hot
import org.scalajs.dom
@JSImport("resources/index.css", JSImport.Default)
@js.native
object IndexCSS extends js.Object
object Main {
val css = IndexCSS
@JSExportTopLevel("main")
def main(): Unit = {
if (LinkingInfo.developmentMode) {
hot.initialize()
}
val container = Option(dom.document.getElementById("root")).getOrElse {
val elem = dom.document.createElement("div")
elem.id = "root"
dom.document.body.appendChild(elem)
elem
}
ReactDOM.render(App.component(App.Props(name = "Slinky user")), container)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment