Skip to content

Instantly share code, notes, and snippets.

@ftes
Created September 5, 2022 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftes/b083f68fa11afe1fd3d2691e35685f37 to your computer and use it in GitHub Desktop.
Save ftes/b083f68fa11afe1fd3d2691e35685f37 to your computer and use it in GitHub Desktop.
Phoenix LiveView Form + HeadlessUI
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()
}
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