Created
September 5, 2022 15:29
-
-
Save ftes/b083f68fa11afe1fd3d2691e35685f37 to your computer and use it in GitHub Desktop.
Phoenix LiveView Form + HeadlessUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class ComboboxFormWebcomponent extends HTMLElement { | |
connectedCallback() { | |
// ... | |
const inputId = this.getAttribute("input-id") | |
this.inputEl = document.getElementById(inputId) | |
this.inputEl.addEventListener("change", this.onValueChange) | |
this.render() | |
} | |
disconnectedCallback() { | |
this.inputEl.removeEventListener("change", this.onValueChange) | |
} | |
render() { | |
// ... | |
const options = JSON.parse(this.getAttribute('options')) | |
const value = this.inputEl.getAttribute('value') | |
const onSelect = ({ value }) => { | |
this.inputEl.value = value | |
// https://hexdocs.pm/phoenix_live_view/js-interop.html#triggering-phx-form-events-with-javascript | |
this.inputEl.dispatchEvent(new Event("input", {bubbles: true})) | |
} | |
this.__reactRoot.render( | |
<Combobox options={options} value={value} onSelect={onSelect} /> | |
) | |
} | |
// ... | |
onValueChange = () => this.render() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule PhoenixHeadlessuiWeb.HomeLive do | |
# ... | |
@impl true | |
def render(assigns) do | |
~H""" | |
<.form let={f} for={@changeset} phx-change="validate" phx-submit="save"> | |
<%= label f, :assignee %> | |
<%= hidden_input f, :assignee, id: "assignee-input" %> | |
<x-combobox-form input-id="assignee-input" phx-update="ignore" id="react-form-combobox" options={Jason.encode!(@options)} /> | |
<%= error_tag f, :assignee %> | |
<%= submit "Save" %> | |
</.form> | |
""" | |
end | |
@impl true | |
def mount(_params, _session, socket) do | |
{:ok, socket | |
|> assign(:options, @options) | |
|> assign(:changeset, Form.changeset(%Form{}))} | |
end | |
# ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment