How to get element after "onClick"

115 Views Asked by At

I use scalajs-react and cannot understand why it does not work

please help, it seems to be easy

<.dev()(^.onClick ==> {(e: ReactEventFromHtml) => handler(e)})

def handler(e: ReactEventFromHtml): Callback = {

  Callback {
    val elem = e.target  //here we get elem = null

    //----- any code ---- 
  }

}
1

There are 1 best solutions below

0
On BEST ANSWER

React re-uses events once it thinks you're finished with them.

Try either

  1. calling .persist on the event to prevent React from re-using it
  2. extract the info you need from the event outside of the Callback. I'll give two examples of how to do that:
def handleBad(e: ReactEventFromHtml): Callback =
  Callback {
    println("target = " + e.target) // <--------- BAD
  }

def handleGood1(e: ReactEventFromHtml): Callback = {
  val target = e.target
  Callback {
    println("target = " + target) // <----------- GOOD
  }
}

def handleGood2(e: ReactEventFromHtml): Callback =
  e.extract(_.target) { target =>
    Callback {
      println("target = " + target) // <--------- GOOD
    }
  }