I've built a simple TreeView with scalajs-react. Each node contains a text field.
I write some text into child 1.1
:
Now, if I add new child 1.2
below 1
, the text disappears because node 1
with all its children gets re-rendered:
When adding a child in this Javascript-Redux TreeView, the siblings are not re-rendered. How can I achieve that with scalajs-react?
See my code below or a minimal example project on GitHub.
case class Node(text: String, children: Vector[Node])
object TreeView {
val childNode = Node("1.1", Vector())
val parentNode = Node("1", Vector(childNode))
val rootNode = ScalaComponent.builder[Unit]("Node")
.initialState(parentNode)
.renderBackend[NodeBackend].build
class NodeBackend($ : BackendScope[Unit, Node]) {
def addChild =
$.modState(
_.copy(children = $.state.runNow().children :+ Node("1.2", Vector())))
def render(node: Node): VdomElement = {
val children =
if (node.children.nonEmpty)
node.children.toVdomArray(child => {
val childNode = ScalaComponent.builder[Unit]("Node")
.initialState(child)
.renderBackend[NodeBackend].build
childNode.withKey(child.text)()
})
else EmptyVdom
<.div(
node.text, <.input(), <.button("Add child", ^.onClick --> addChild),
children
)
}
}
def apply() = rootNode()