Building Better UI Components: Elm Ports with Web Components
One of the most common questions I get about Elm is: “How do I integrate it with existing JavaScript ecosystems?” While Elm’s isolation is a strength, real-world projects often require working with external libraries, APIs, or UI components. Doing incremental migration is also the recommended way to introduce Elm, and luckily there are may ways to accomplish this.
Today, I’ll show you how to combine two powerful technologies:
- Elm Ports: The official way to communicate between Elm and JavaScript
- Web Components: Standard, framework-agnostic UI components
This combination gives us the best of both worlds: Elm’s type safety and predictable architecture alongside the reusability and interoperability of Web Components. Let’s dive in!
What we’re building
You know what? Let’s embed it:
What Are Elm Ports?
Ports are Elm’s sanctioned escape hatch to JavaScript. Or put another way: They facilitate treating JavaScript as mere IO device. Specifically they allow your Elm application to:
- Send data out to JavaScript (outgoing port)
- Receive data from JavaScript (incoming port)
Think of ports as message channels between Elm’s pure world and JavaScript’s wild west.
What Are Web Components?
Web Components are a set of standardized browser APIs that allow you to create reusable, encapsulated components using plain JavaScript, HTML, and CSS. The key technologies include:
- Custom Elements: Create your own HTML tags
- Shadow DOM: Encapsulated DOM and styles
- HTML Templates: Reusable markup structures
Once defined, Web Components work in any framework (or no framework) - making them ideal for sharing UI elements across different projects.
Why Combine Them?
- Use specialized UI libraries not available in Elm
- Share components across projects using different frameworks
- Gradually migrate existing applications to Elm
- Integrate third-party tools (maps, charts, rich text editors)
The Example Project: A Color Picker
Let’s build a simple example: an Elm application that uses a Web Component color picker. We’ll:
- Create a simple Elm app that displays the selected color
- Integrate a color-picker Web Component
- Use ports to communicate between them
Step 1: Setting Up the Elm Application
First, let’s create our core Elm application:
1port module Main exposing (main)
2
3import Browser
4import Html exposing (..)
5import Html.Attributes exposing (..)
6import Json.Decode as Decode
7import Json.Encode as Encode
8
9-- PORTS
10
11port sendColor : String -> Cmd msg
12port receiveColor : (String -> msg) -> Sub msg
13
14-- MODEL
15
16type alias Model =
17 { currentColor : String
18 }
19
20init : () -> ( Model, Cmd Msg )
21init _ =
22 ( { currentColor = "#3366ff" }
23 , sendColor "#3366ff" -- Initialize the color picker with our default
24 )
25
26-- UPDATE
27
28type Msg
29 = ColorChanged String
30
31update : Msg -> Model -> ( Model, Cmd Msg )
32update msg model =
33 case msg of
34 ColorChanged newColor ->
35 ( { model | currentColor = newColor }
36 , Cmd.none
37 )
38
39-- SUBSCRIPTIONS
40
41subscriptions : Model -> Sub Msg
42subscriptions _ =
43 receiveColor ColorChanged
44
45-- VIEW
46
47view : Model -> Html Msg
48view model =
49 div [ style "padding" "2rem", style "font-family" "system-ui, sans-serif" ]
50 [ h1 [] [ text "Elm + Web Components" ]
51 , div []
52 [ p [] [ text "Selected color: ", strong [] [ text model.currentColor ] ]
53 , div
54 [ style "width" "100px"
55 , style "height" "100px"
56 , style "background-color" model.currentColor
57 , style "margin" "1rem 0"
58 , style "border-radius" "4px"
59 ]
60 []
61 , div []
62 [ -- Our Web Component will be placed here
63 node "color-picker"
64 [ attribute "current-color" model.currentColor
65 ]
66 []
67 ]
68 ]
69 ]
70
71-- MAIN
72
73main : Program () Model Msg
74main =
75 Browser.element
76 { init = init
77 , view = view
78 , update = update
79 , subscriptions = subscriptions
80 }
In this Elm code, we’ve:
- Defined two ports:
sendColorto send the current color to JavaScript, andreceiveColorto receive color changes - Used
nodeto insert our custom element (which we’ll create next) - Set up the appropriate model, update, and subscription functions
Step 2: The JavaScript Glue
Next, we need to initialize Elm and wire up our ports:
1// index.js
2
3// Init Elm app
4const app = Elm.Main.init({ node: document.querySelector("main") });
5
6// Define our color-picker Web Component
7class ColorPicker extends HTMLElement {
8 constructor() {
9 super();
10 this.attachShadow({ mode: "open" });
11 this._app = null; // Will store reference to Elm app
12 this._boundHandler = this._handleColorChange.bind(this);
13 this.render();
14 }
15
16 // Connect to DOM - add event listeners
17 connectedCallback() {
18 this._attachEventListeners();
19 }
20
21 // Clean up when removed from DOM
22 disconnectedCallback() {
23 this._detachEventListeners();
24 }
25
26 // Add event listeners to the input
27 _attachEventListeners() {
28 const input = this.shadowRoot.querySelector("input");
29 if (input) {
30 input.addEventListener("input", this._boundHandler);
31 }
32 }
33
34 // Remove event listeners from the input
35 _detachEventListeners() {
36 const input = this.shadowRoot.querySelector("input");
37 if (input) {
38 input.removeEventListener("input", this._boundHandler);
39 }
40 }
41
42 // Handle color changes from the input
43 _handleColorChange(event) {
44 const newColor = event.target.value;
45 this.setAttribute("current-color", newColor);
46
47 // Send the color back to Elm
48 if (this._app && this._app.ports && this._app.ports.receiveColor) {
49 this._app.ports.receiveColor.send(newColor);
50 }
51 }
52
53 // Store reference to Elm app
54 setApp(app) {
55 this._app = app;
56 }
57
58 // Watch for attribute changes
59 static get observedAttributes() {
60 return ["current-color"];
61 }
62
63 // Handle attribute changes
64 attributeChangedCallback(name, oldValue, newValue) {
65 if (name === "current-color" && oldValue !== newValue) {
66 // Update the input value directly if possible
67 const input = this.shadowRoot.querySelector("input");
68 if (input && input.value !== newValue) {
69 input.value = newValue;
70 } else {
71 // Otherwise re-render
72 this.render();
73 this._attachEventListeners();
74 }
75 }
76 }
77
78 get currentColor() {
79 return this.getAttribute("current-color") || "#000000";
80 }
81
82 render() {
83 this.shadowRoot.innerHTML = `
84 <style>
85 :host {
86 display: block;
87 font-family: inherit;
88 }
89 .picker-container {
90 display: flex;
91 align-items: center;
92 gap: 8px;
93 }
94 label {
95 font-weight: bold;
96 }
97 input[type="color"] {
98 width: 50px;
99 height: 30px;
100 border: none;
101 border-radius: 4px;
102 }
103 </style>
104 <div class="picker-container">
105 <label for="color-input">Pick a color:</label>
106 <input type="color" id="color-input" value="${this.currentColor}">
107 </div>
108 `;
109 }
110}
111
112// Register the Web Component
113customElements.define("color-picker", ColorPicker);
114
115// Set up communication from Elm to the Web Component
116app.ports.sendColor.subscribe((color) => {
117 // Find our color picker element
118 const picker = document.querySelector("color-picker");
119 if (picker) {
120 // Give the Web Component a reference to the Elm app
121 if (!picker._app) {
122 picker.setApp(app);
123 }
124 // Update the color
125 picker.setAttribute("current-color", color);
126 }
127});
This update ensures that the JavaScript code in the blog post matches exactly with the code from foo.html.
Step 3: HTML Setup
Finally, we need a simple HTML file to bring it all together:
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Elm + Web Components</title>
7 <script src="index.js"></script>
8 <script src="elm.js"></script>
9 </head>
10 <body>
11 <div id="elm-app"></div>
12 </body>
13</html>
How It Works
The data flow in our application follows this pattern:
Elm → JavaScript:
- Elm sends the current color through the
sendColorport - JavaScript receives this value and updates the Web Component’s attribute
- Elm sends the current color through the
Web Component → JavaScript → Elm:
- User interacts with the color picker
- Web Component fires an event
- The event handler sends the new color to Elm via the
receiveColorport - Elm updates its model with the new color
This clean separation maintains Elm’s purity while leveraging the native capabilities of the web platform.
Real-World Considerations
1. More Complex Data
For our simple example, we’re just passing strings. For complex data, you’ll need to encode/decode JSON:
1-- In Elm
2port sendComplexData : Encode.Value -> Cmd msg
3port receiveComplexData : (Decode.Value -> msg) -> Sub msg
4
5-- Using it
6sendComplexData (Encode.object
7 [ ("color", Encode.string model.color)
8 , ("opacity", Encode.float model.opacity)
9 , ("name", Encode.string model.name)
10 ])
1// In JavaScript
2app.ports.sendComplexData.subscribe((data) => {
3 console.log(data.color, data.opacity, data.name);
4});
2. Error Handling
When receiving data from JavaScript, always be prepared for unexpected values:
1type Msg
2 = GotColorData (Result Decode.Error ColorData)
3
4subscriptions : Model -> Sub Msg
5subscriptions _ =
6 receiveComplexData (decodeColorData >> GotColorData)
7
8decodeColorData : Decode.Value -> Result Decode.Error ColorData
9decodeColorData value =
10 Decode.decodeValue colorDataDecoder value
3. Multiple Components
With multiple Web Components, maintain a clear naming convention for your ports:
1port sendColorPickerData : Encode.Value -> Cmd msg
2port receiveColorPickerData : (Decode.Value -> msg) -> Sub msg
3
4port sendMapData : Encode.Value -> Cmd msg
5port receiveMapData : (Decode.Value -> msg) -> Sub msg
How This Relates to Clean Architecture
This ports + Web Components pattern aligns perfectly with Clean Architecture principles:
Separation of Concerns:
- Elm handles application logic
- Web Components handle specialized UI rendering
- Ports define clear boundaries between systems
Dependency Rule:
- Core business logic in Elm doesn’t depend on the Web Component details
- The outer layer (JavaScript) depends on the inner layer (Elm), not vice versa
Testability:
- Elm code can be tested without Web Components
- Ports can be mocked for testing
- Web Components can be tested in isolation
This approach gives us the best of both worlds:
- Elm’s strengths: Type safety, immutability, and predictable state management
- Web Components’ strengths: Standards-based, reusable UI components
Conclusion
The combination of Elm ports and Web Components offers a powerful way to build robust applications while still leveraging the best tools from the broader web ecosystem. This approach maintains the benefits of Elm’s architecture while embracing the interoperability of web standards.
By keeping your core application logic in Elm and using Web Components only for specialized UI needs, you get a clean, maintainable architecture with clear boundaries.
Have you used Elm ports or Web Components in your projects? I’d love to hear about your experiences, feel free to add feedback using my new feedback tool, Feedback.one.
Resources
Note: This blog post is intended for developers with basic knowledge of both Elm and Web Components. If you’re new to Elm, check out the official guide first.