DEV Community

loading...

Refactoring Evan's viewInput function in elm-todomvc

dwayne profile image Dwayne Crooks ・1 min read

I don't like that we have to write our own onEnter function to make viewInput work.

By wrapping the input element in a form element we can achieve the same goal, write simpler code and keep the HTML semantic.

viewInput : String -> Html Msg
viewInput task =
  header
    [ class "header" ]
    [ h1 [] [ text "todos" ]
    , form
        [ onSubmit Add ]
        [ input
            [ class "new-todo"
            , placeholder "What needs to be done?"
            , autofocus True
            , value task
            , name "newTodo"
            , onInput UpdateField
            ]
            []
        ]
    ]
Enter fullscreen mode Exit fullscreen mode

Now when you type a description and press ENTER a submit event is fired on the form. The onSubmit event handler detects the submit event with preventDefault and propagates the Add message to the update function.

What do you think? Is this version any better?

Discussion

pic
Editor guide
Collapse
francescortiz profile image
Francesc Ortiz

This version is the standard way of programmatically doing HTML forms. This is the way to benefit of all the features that the browser can provide to help the user. You use the onEnter or other hacks when you need nonstandard functionality.