Displaying Modals/Popups in Elm
While working on a somewhat bigger Elm project, built using (my CSS framework of choice these days) Bulma. I wanted to use modals/popups for some features. Quick search landed me to some packages like Dialog, Diyalog.
But something felt wrong, Bulma already has support for modals, it clicked to me that I can show/hide Bulma modals using some flag in the Model, the way I used it in React/Bootstrap projects.
So my Model looks something like..
type alias Model =
{ projectName: String, isPopUpActive: Bool }
And Msg for toggling the modal
type Msg
= TogglePopup
In update, we simply toggle isPopUpActive in model
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
TogglePopup ->
( { model
| isPopUpActive = not model.isPopUpActive
}
, Cmd.none
)
Here goes the most important part.. the View
On line #12, we conditionally render the modal if the flag is True.
On line #8, we send TogglePopup msg onClick on the button, which will show the popup.
On line #23, 29 and 35, we again send TogglePopup msg, which will hide the popup.
“Modal contents” can be anything you like; even forms, with msgs sent to main update.
And that’s it. We have got a modal working without using any packages!
This can be easily customized to work for displaying multiple types of Modals or entirely different CSS framework like Bootstrap or Semantic-UI if that’s your favorite.