Statefull sub-component example
See original GitHub issueAfter going through documentation and examples, I was stumped over how to build react components in scala that included a Backend and could be used conveniently by parent components as none of the sub-components included Backends. https://github.com/tastejs/todomvc/tree/master/examples/scalajs-react provided a good mechanism but that example is a little bit much, it might be better to have a shorter example like the one below included in your examples.
object Counter {
case class Props(name: String, inc: () => Callback)
case class State(count: Int)
class Backend($: BackendScope[Props, State]) {
def increment():Callback = $.modState(s => State(s.count+1))
}
def render(P: Props, S:State): ReactElement = {
<.div(
^.input(
^.`type` := "button",
^.value := "+",
^.onClick --> { P.inc().runNow() ; increment() }
),
s" ${P.name}: ${S.count}"
)
}
}
val component = ReactComponentB[Props]("Counter")
.initialState_P(p => State(0))
.renderBackend[Backend]
.build
def apply( s:String, inc: () => Callback): ReactElement = component(Props(s,inc))
}
object TotalCounters {
case class Props(title: String)
case class State(total: Int)
class Backend($: BackendScope[Props, State]) {
def incTotal() = $.modState(s => State(s.total+1))
def render(P: Props, S:State): ReactElement = {
<.div(
<.h1(P.title),
Counter("John",incTotal),
Counter("Fred",incTotal),
Counter("Jack",incTotal),
<.input(
^.`type` := "button",
^.value := "Reset total",
^.onClick --> $.setState(State(0))
),
s" Total: ${S.total}"
)
}
}
val component = ReactComponentB[Props]("Counters")
.initialState_P(p => State(0))
.renderBackend[Backend]
.build
def apply( title: String ): ReactElement = component(Props(title))
}
So, if you are interested in a PR I can create one, but if you have no interest in adding that then there’s no point me creating the PR. If you would be interested in a PR, then I probably need to fix some things in this example than I am doing wrong and instruction would be welcome.
If the neo branch was going to be ready fairly soon then it might not be worth your time.
Issue Analytics
- State:
- Created 7 years ago
- Comments:5 (4 by maintainers)
You remind me that I was going to publish usage guidelines ages ago but forgot. I even wrote up a heap of stuff. Even better though would be something collaborative where community can contribute patterns/suggestions and multiple people suggest pros/cons, highlight trade-offs etc. That’d be cool.
While I still haven’t gotten around to publishing general usage guidelines and gotchas, I have done so for
Callback
recently seeing as it caused some confusion. Anyway this is resolved so closing.