ScalaJS frontend router

scalajs-router Maven Central Build Status

ScalaJS frontend router.

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

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

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 => 

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)