ScalaJS React onClick handler using router for the wrapped component

583 Views Asked by At

I'm wrapping Bootstrap React for use in the Japgolly ScalaJS React and have come up with the following:

case class NavItem(
   onClick: UndefOr[js.Function1[ReactEvent, Boolean]] = undefined,
   // ...
) { /* ... create method here */ }

object NavItem {
   def toPage[T](page: T, children: ReactNode*)(implicit ctl: RouterCtl[_ >: T]) = {
     val clickFunction: js.Function1[ReactEvent, Boolean] = { e: ReactEvent =>
       e.preventDefault()
       ctl.set(page).runNow()
       true
     }

     NavItem(
       key = page.toString,
       href = ctl.pathFor(page).value,
       onClick = clickFunction
     ).create(
       children
     )
   }
}

This works, but I feel is more complicated than it could be.

My first idea was to use onClick : UndefOr[ReactEvent => Callback] instead which seems more in line with the japgolly ScalaJS React usual approach, so I tried:

val clickEvent: ReactEvent => Callback = e => {
  e.preventDefault()
  ctl.set(page)
}

This compiles but the page is never switched even though debugging shows that the callback is invoked. Why is the page never switched in this case?

Any suggestions on how to properly do a NavItem which shows the link as it will be when clicking the link, but uses the router to actually route? What's the idiomatic way?

1

There are 1 best solutions below

1
On

You don't need the onClick handler - just remove it and it should work as expected. The href populated with router.pathFor is enough for routing.