scala.jsscalajs-react

Radiobutton click event invoking callback 2 times


I have a radio button defined as:

<.label(
        ....styling
        ^.onClick ==> { event =>
          event.stopPropagation()
          props.select
        },
        <.input.radio(
          ....styling
          ^.onChange ==> { event =>
            event.preventDefault()
            Callback.empty
          },
          ^.checked := props.isActive,
          ^.disabled := props.disabled
        )
      )

So basically I aim to invoke a callback(props.select) on click of the radio button, and stop further propagation(hence event.stopPropagation). Also, on change event I want default operation not to happen(hence event.preventDefault).

But I observe that callback(props.select) is invoked 2 times when radiobutton is clicked.

What am I missing here?


Solution

  • Two things.

    Firstly, because it's a side-effect, you should be wrapping event.preventDefault() in a callback. So either Callback(event.preventDefault()) or you can use the helper method event.preventDefaultCB.

    Secondly, React likes to invoke things twice in dev mode, (it's not a scalajs-react thing). There's https://github.com/facebook/react/issues/12856#issuecomment-390206425 and there are a bunch of other examples on SO. Try searching for just React instead of scalajs-react.