1

I have an elm application that is working fine. It has a navigation bar that we built using standard elm UI functional code. Someone sees my app and says you should be using our standard javascript toolbar UI component. Is it possible to embed a Javascript UI component into a 100% native ELM app?

Note, we already are using ports to call some native JavaScript functions. I am wondering if the same concept can be used to embed UI components but since ELM has it's own internal rendering would this be problematic?

2 Answers 2

8

It's not clear to me what you mean by "Javascript UI components" since that could refer to many different things such as react components or angular components. But Elm does support standard Web Components through Custom Elements.

Here's an incomplete example of what it looks like on the Elm side, borrowed (and redacted a bit) from Beginning Elm:

googleMap : List (Attribute a) -> List (Html a) -> Html a
googleMap =
    Html.node "google-map"


onGoogleMapDrag : Attribute Msg
onGoogleMapDrag =
    coordinatesDecoder
        |> Json.Decode.map UpdateCenter
        |> on "google-map-drag"


view : Model -> Html Msg
view model =
    googleMap
        [ attribute "latitude" (toString model.center.latitude)
        , attribute "longitude" (toString model.center.longitude)
        , attribute "drag-events" "true"
        , attribute "zoom" "5"
        , onGoogleMapDrag
        ]
        (List.map viewMarker model.markers)
Sign up to request clarification or add additional context in comments.

2 Comments

I believe these are NPM packages and they are written using Preact and Redux. Maybe that makes it clearer? They are not web components.
If you can make them into web components you can use them, and I think there's a good chance that you can. But if you can't, you can't, unfortunately.
4

This is what you need to know:

  1. Elm let's you render a "custom" HTML node via Html.node
  2. Most browsers (and more with the help of a polyfill allow you can create a custom element that uses JS to render itself.

So, your Elm code says I want to render a <my-custom-thing customProp="whatever"/>. Elm is responsible for putting that node in the dom, and removing it.

Your custom element and JS do the work of rendering what occurs inside that node.

Your custom element can send events back to Elm (e.g. hovers, clicks, custom stuff).

Ports are more for processing. You have data that you want to send between Elm/JS. If you send data over a port to JS, and JS alters the DOM, you'll likely have a problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.