purescriptpurescript-halogen

purescript halogen - render elements or nothing conditionally


I have a utility function to conditinally render elements:

thanRender :: ∀ w i. Boolean -> EL.HTML w i -> EL.HTML w i
thanRender true h = h
thanRender _    _ = EL.text ""

Usage:

isJust state.foo `thanRender` (EL.h1_ [ EL.text state.title ])

Is there a better way to "render nothing" as to render EL.text "" ?


Solution

  • Since Halogen doesn't allow maybe elements in render, the best way is as you have it returning EL.text "" to indicate no value. You can see it used in the Real World Halogen example.

    The other alternative if you're using child elements is to return an array, using a singleton array when the value is true and an empty array with the value is false:

    thenRender :: forall w i. Boolean -> (Unit -> EL.HTML w i) -> Array (EL.HTML w i)
    thenRender cond f = if cond then [ f unit ] else []
    
    render _ =
      EL.div_
        $ (isJust state.foo `thenRender` \_ -> EL.h1 [ EL.text state.title ])
        <> renderOtherChildren
    

    This doesn't work for the top-level render element since it needs to be a single element rather than an array of elements. Personally I think the first way you have it as is cleaner.