18

I'm writing a function that displays error messages, so in my view, I have something like

div [] [ displayErrors model ]

in the event that there are no errors, how can I make displayErrors return something that is interpreted as an empty Html node?

2 Answers 2

29

You can use an Html.text node with an empty string:

emptyNode = Html.text ""
2
  • 3
    Does this get optimized away? I'm concerned about using these phantom nodes because of the possibility of triggering some CSS rule that leads to unintended results.
    – jz87
    Jul 27, 2016 at 15:26
  • @jz87 looks like nothing gets rendered
    – rpearce
    Jan 8, 2017 at 5:45
10

@robertjlooby's answer looks perfectly fine to me.

However, if you really want not to have any node, you could make displayErrors return a Maybe (Html msg).

Then, you can change your code to the following:

import Maybe.Extra exposing (maybeToList)

div [] ( displayErrors model |> maybeToList )

When displayErrors returns Nothing, the div will be really empty.

Note: you can install the Maybe.Extra module with the following command:

elm package install elm-community/maybe-extra
2
  • Yeah, this is a nice solution. The only problem is, if I'm using this in a list. So for example: div [] [ stuff, (displayErrors model |> maybeToList) ], this wouldn't really work. I guess there is no really good way to address this with the existing Html function signatures. Maybe the return signature should be Maybe (Html Msg) instead of Html Msg.
    – jz87
    Jul 29, 2016 at 21:13
  • 1
    In that case you can concatenate lists: div [] ([stuff] ++ (displayErrors model |> maybeToList))
    – Zimm i48
    Jul 30, 2016 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.