For some reason, this general goal is called “Single Page Apps” or SPAs in the JavaScript world. It is odd in that the essence is that you want to manage multiple pages intelligently, and maybe “asset management” would have been clearer, but that ship has sailed.
The core functionality is the ability to “navigate” to new URLs, changing the address bar of the browser without the browser kicking off a request to your servers. Instead, you manage the changes yourself in Elm.
Handling Routing in Elm
Gonna need some helpful libraries
Elm Navigation
program : (Location -> msg) ->
{ init : Location -> (model, Cmd msg)
, update : msg -> model -> (model, Cmd msg)
, subscriptions: model -> Sub msg
, view : model -> Html msg
} -> Program Never model msg
Pretty sure we want the 3rd one. We want to fetch the data, and when’s it’s successfully back we want to render that particular view to the app
elm-package install elm-lang/navigation -y
we’ll start with a #hash routing system for simplicity and then grow it from there.
import Navigation
Update the program to be a navigation program that will take the inital and UrlChange
which is a type of Msg
main : Program Never Model Msg
main =
Navigation.program UrlChange
{ view = view
, init = init
, update = update
, subscriptions = always Sub.none
}
init : Navigation.Location -> ( Model, Cmd Msg )
init location =
( { route = Home }, Cmd.none )
case msg of
UrlChange location ->
case location.hash of
#
Let’s render a list of items as our nav menumenu =
ul [] (List.map viewLinks [ "home", "about", "contact", "Bob" ])
Each viewLink will just be an ‘a’ tag with the corresponding href
Routing practice
Figure out if rendering a react component in Elm is a good idea or not?
JavaScript to Elm
Jesse Tomchak