sake92 / scalajs-router

ScalaJS frontend router

Version Matrix

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 "/users/1" => UserDetailsComponent(1)
}

Router("main", routes, NotFoundComponent).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)
}