This doc https://github.com/japgolly/scalajs-react/blob/master/doc/USAGE.md#refs is a bit unclear.
I've created small example: "squareViewer" showes "square" by click
How can I get Ref to component "square" in method squareViewer.Backend.show?
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
object squareViewer {
class Backend($: BackendScope[Unit, Unit]) {
def show() = Callback {
//???
//val r = ref to square instance
//r.backend.show()
}
def render() = {
<.div(
<.button("Show square", ^.onClick-->show()),
square.component.withRef("id1")()
)
}
}
val component = ReactComponentB[Unit]("squareViewer")
.renderBackend[Backend]
.buildU
}
object square {
case class State(visible: Boolean)
class Backend($: BackendScope[Unit, State]) {
def show() = $.setState(State(true))
def hide() = $.setState(State(false))
def render(s: State) = {
<.div("Yo!",
^.width:="100px", ^.height:="100px",
^.position:="absolute", ^.top:=0, ^.left:=0,
^.fontSize:="300%",
^.backgroundColor:="red",
!s.visible ?= ^.display.none,
^.onClick-->hide()
)
}
}
val component = ReactComponentB[Unit]("square")
.initialState(State(false))
.renderBackend[Backend]
.buildU
}
this should do the trick:
Edit: Correted a typo, this should work now.