Rendering custom elements in Elm

In Elm, we can create custom elements using the Html.custom function, which defines the attributes and behavior of the element. Let's create a simple custom element called CustomButton that displays a button with a custom style and increments the count when clicked.

The CustomButton example

Here's the full example:

{
    "type": "application",
    "source-directories": [
        "src"
    ],
    "elm-version": "0.19.1",
    "dependencies": {
        "direct": {
            "elm/browser": "1.0.2",
            "elm/core": "1.0.5",
            "elm/html": "1.0.0",
            "elm/json": "1.1.3"
        },
        "indirect": {
            "elm/time": "1.0.0",
            "elm/url": "1.0.0",
            "elm/virtual-dom": "1.0.3"
        }
    },
    "test-dependencies": {
        "direct": {},
        "indirect": {}
    }
}
The CustomButton example

Explanation

Lines 3–4: The program imports necessary modules like Browser, Html, Html.Attributes, and Html.Events to use their functionalities.

Lines 8–17: The Model type alias represents the application's state, which includes a single field clickCount to store the number of times the button is clicked. The init function initializes the model by setting clickCount to 0.

Lines 19–28: The Msg type is a custom type that defines different kinds of messages the application can handle. Here, there's only one message type, ButtonClicked, which will be triggered when the button is clicked. The update function takes a message (Msg) and the current model and returns the updated model. When it receives the ButtonClicked message, it increments the clickCount field in the model by 1.

Lines 30–37: The view function takes the current model and returns the HTML representation of the view. The view contains two parts:

  • A div element that displays the current count.

  • A button element with a custom CSS class and an onClick event that sends the ButtonClicked message when clicked.

Lines 39–47: The main function is the entry point of the application. It uses Browser.sandbox to create a simple interactive Elm program. It specifies the initial state (init), the update function (update), and the view function (view) to handle the rendering.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved