ScalaJS-React Router

Install dependency

import org.scalajs.linker.interface.ModuleSplitStyle
 
lazy val myapp = project
  .in(file("."))
  .enablePlugins(ScalaJSPlugin)
  .settings(
    scalaVersion := "3.3.3",
    scalaJSUseMainModuleInitializer := true,
    scalaJSLinkerConfig ~= {
      _.withModuleKind(ModuleKind.ESModule)
        .withModuleSplitStyle(
          ModuleSplitStyle.SmallModulesFor(List("myapp"))
        )
    },
    libraryDependencies ++= Seq(
      "org.scala-js" %%% "scalajs-dom" % "2.4.0",
      "com.github.japgolly.scalajs-react" %%% "core" % "2.1.1",
      "com.github.japgolly.scalajs-react" %%% "extra" % "2.1.1"
    )
  )

Usage

Update the App.scala file:

package myapp
 
import org.scalajs.dom
 
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.html_<^._
import japgolly.scalajs.react.extra.router.{
  RouterConfigDsl,
  BaseUrl,
  Router,
  SetRouteVia
}
 
val HomePage = ScalaComponent.static("Home")(<.h3("Home"))
 
val AboutPage =
  ScalaComponent.static("About")(<.h3("About"))
 
object AppRouter {
  sealed trait Page
  case object Home extends Page
  case object About extends Page
 
  val config = RouterConfigDsl[Page].buildConfig { dsl =>
    import dsl._
    (emptyRule
      | staticRoute(root, Home) ~> render(HomePage())
      | staticRoute("/about", About) ~> render(AboutPage()))
      .notFound(redirectToPage(Home)(SetRouteVia.HistoryReplace))
  }
 
  val baseUrl = BaseUrl.fromWindowOrigin
  val router = Router(baseUrl, config)
}
@main
def MyApp(): Unit =
  val root = dom.document.querySelector("#app")
  AppRouter.router().renderIntoDOM(root)

Visit: http://localhost:5173/about

Last Update: 08:02 - 26 April 2024

On this page