Web Components

Demonstrates how to integrate htmx with web components and shadow DOM

HOME | Explain | Code | Htmx Docs | Full screen
from fasthtml.common import fast_app, Script, Article, ft_hx

js = """
customElements.define('my-component', class MyComponent extends HTMLElement {
  // This method runs when your custom element is added to the page
  connectedCallback() {
    const root = this.attachShadow({ mode: 'closed' })
    root.innerHTML = `
      <button hx-get="/my-component-clicked" hx-target="next div">Click me!</button>
      <div></div>
    `
    htmx.process(root) // Tell HTMX about this component's shadow DOM
  }
})
"""

app, rt = fast_app(hdrs=[Script(js)])


@app.get
def page():
    MyComponent = ft_hx("my-component")
    # Alternative: NotStr(MyComponent())
    return Article(MyComponent())


@app.get("/my-component-clicked")
def example():
    return "Clicked!"

Server Calls