sporto / hop

[Deprecated] Navigation and routing helpers for single page applications in Elm
MIT License
293 stars 21 forks source link

Provide a helper to render <a> tag with href, onClick and preventDefault #39

Open ffigiel opened 7 years ago

ffigiel commented 7 years ago

All examples seem to use buttons with onClick event handlers, which is convenient but bad for UX. For example, what if a user wants to open a link in a new tab?

I've been looking for a way to employ a tags for navigation purposes and I came up with this:

link : Route -> List (Attribute Msg) -> List (Html Msg) -> Html Msg
link route attrs =
  a
    (List.append
      attrs
      [ href (Routing.reverse route)
      , onClick (NavigateTo route)
      ]
    )

...and this works, but clicking on a link now does a full page reload 😕 I could use a custom click handler with preventDefault, but at that point I'd rather seek guidance in the library API or docs - is there a better way to handle this?

sporto commented 7 years ago

I haven't come across a better way to do this. So preventDefault is the way to do it. http://package.elm-lang.org/packages/elm-lang/html/1.1.0/Html-Events#onWithOptions

I'll look into adding this combination as a convenience function.

ffigiel commented 7 years ago

Here's the custom click handler:

onClickSimply : Msg -> Attribute Msg
onClickSimply msg =
  onWithOptions
    "click"
    { stopPropagation = False
    , preventDefault = True
    }
    (Json.Decode.succeed msg)

oh, your reply just popped in when I was about to submit it. Yep, onWithOptions is the only way it seems...