sake92 / scalajs-router   0.0.9

Apache License 2.0 GitHub

ScalaJS frontend router

Scala versions: 2.13
Scala.js versions: 1.x

scalajs-router Maven Central Build Status

ScalaJS frontend router.

In your HTML add data-navigate attribute to nav elements:

<nav>
  <button data-navigate="/home">Home</button>
  <button data-navigate="/users/1">User details</button>
</nav>

Create element where router will show your dynamic content:

<div id="main"></div>

Then specify your routes and bind the router:

val routes: Router.Routes = {
  case "/home"        => HomeComponent
  case s"/users/$id"  => UserDetailsComponent(id.toLong)
  case _              => NotFoundComponent
}

Router("main", routes).init()

// components
object HomeComponent extends Component {
  def asElement: Element = ...
}
case class UserDetailsComponent(userId: Long) extends Component ..
object NotFoundComponent extends Component ..

You can attach a listener when a route changes:

Router().withListener {
  case "/active"    => // do something...
  case "/other"     => 
  case whateverElse => 
}.init()

With @Route macro you can simplify your routes matching to this:

@Route class HomeRoute(p1: "home")()
@Route class UserDetailsRoute(p1: "users", val userId: Long)()

val routes: Router.Routes = {
  case HomeRoute()              => HomeComponent
  case UserDetailsRoute(userId) => UserDetailsComponent(userId)
}