Labeled Checkboxes
Follow along in the .
That will let people toggle the checkboxes, and using means they get a much bigger area they can click on. Let’s write an Elm program that manages all this interaction! As always, we will take a guess at our Model
. We know we need to track the user’s settings so we will put them in our model:
From there, we will want to figure out our messages and update function. Maybe something like this:
This is not too crazy, but we are repeating ourselves a bit. How can we make our view
function nicer? If you are coming from JavaScript, your first instinct is probably that we should make a “labeled checkbox component” but it is easier to just create a helper function! Here is the function with a checkbox
helper function:
Now we have a highly configurable checkbox
function. It takes two arguments to configure how it works: the message it produces on clicks and some text to show next to the checkbox. Now if we decide we want all checkboxes to have a certain , we just add it in the checkbox
function and it shows up everywhere! This is the essense of reusable views in Elm. Create helper functions!