japgolly / scalajs-react

Facebook's React on Scala.JS
https://japgolly.github.io/scalajs-react/
Apache License 2.0
1.64k stars 231 forks source link

Ref not always set #1072

Closed cquiroz closed 2 years ago

cquiroz commented 2 years ago

The code below is a minimal repro of code setting a ref. I was a bit surprised that most of the ttime it prints null but sometimes the actual div. I expected it to be always not null:

@JSExportTopLevel("ReproMain")
object ReproMain {
  val component =
    ScalaFnComponent
      .withHooks[Unit]
      .useRefToAnyVdom
      .render { (_, ref) =>
        // val r = <.div(^.untypedRef := ref, "Test")
        val r = <.div("Test").withRef(ref)
        println(s"cur ${ref.raw.current}")
        r
      }

  @JSExport
  def main(): Unit = {

    val container = Option(dom.document.getElementById("root")).getOrElse {
      val elem = dom.document.createElement("div")
      elem.id = "root"
      dom.document.body.appendChild(elem)
      elem
    }

    component().renderIntoDOM(container)
    ()
  }
}

I need access to current to integrate with a third-party library

japgolly commented 2 years ago

Have you tried this in plain JS? I'm expecting you'll see the same behaviour

cquiroz commented 2 years ago

I probably misunderstood the logic and the facade I'm trying to do is a bit eccentric. Anyway I found how to solve this.