Phoenix LiveView guide

Copy Markdown View Source

This guide wires echarts into a Phoenix application: the asset plug, the LiveView hook, a chart component, live updates and browser events.

The example assumes a Phoenix 1.8 application with LiveView.

1. Dependencies

# mix.exs
def deps do
  [
    {:echarts, "~> 0.1"},
    {:phoenix_live_view, "~> 1.0"}
  ]
end

echarts declares phoenix_live_view and plug as optional dependencies, so your application keeps control of their versions.

2. Serve the assets

# lib/my_app_web/router.ex
defmodule MyAppWeb.Router do
  use MyAppWeb, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_live_flash
    plug :put_root_layout, html: {MyAppWeb.Layouts, :root}
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

  scope "/", MyAppWeb do
    pipe_through :browser

    forward "/echarts", ECharts.Phoenix.Plug
    live "/dashboard", DashboardLive
  end
end

The plug serves /echarts/echarts.min.js, the GL/plugin bundles and the JavaScript clients. Only an allowlist of bundled files is served, with immutable caching.

If the plug is not mounted, the client falls back to jsDelivr. Mounting it is recommended: charts then work offline and do not depend on a third party.

3. Register the hook

// assets/js/app.js
import { EChartsHook } from "../../deps/echarts/priv/static/echarts_hook.js"

let liveSocket = new LiveSocket("/live", Socket, {
  params: {_csrf_token: csrfToken},
  hooks: { EChartsHook }
})

If you already import ECharts through a bundler and expose window.echarts, the hook reuses it and skips the bundle download.

4. Render a chart

defmodule MyAppWeb.DashboardLive do
  use MyAppWeb, :live_view

  alias ECharts

  def mount(_params, _session, socket) do
    chart =
      ECharts.Express.line(
        [%{"month" => "Jan", "sales" => 42}, %{"month" => "Feb", "sales" => 55}],
        x: "month",
        y: "sales",
        title: "Monthly sales",
        height: 420
      )

    {:ok, assign(socket, chart: chart)}
  end

  def render(assigns) do
    ~H"""
    <div class="p-6">
      <ECharts.Phoenix.Component.echarts
        id="sales"
        chart={@chart}
        class="h-96 w-full"
      />
    </div>
    """
  end
end

chart can be an ECharts.Chart or a raw ECharts option map. When the assign changes, the hook updates the existing instance in place.

The container defaults to the chart height. Pass class or style to size it with your own CSS; the hook also resizes the chart with ResizeObserver.

5. Update without re-rendering the differ

Assigning a new chart re-renders the option through LiveView's DOM differ. For large series, push the chart through an event instead:

def handle_event("refresh", _params, socket) do
  chart = build_chart()
  {:noreply, ECharts.Phoenix.push_update(socket, "sales", chart)}
end

The hook listens for "echarts:update" and only handles payloads whose id matches its container.

6. Receive browser events

The chart forwards the events listed in its :events option (default: "click" and "legendselectchanged"):

chart = ECharts.new(option, events: [:click, :datazoom])
def handle_event("echarts_event", %{"type" => type, "data" => data}, socket) do
  {:noreply, assign(socket, last_event: {type, data})}
end

The payload is JSON-safe: seriesIndex, seriesName, name, dataIndex, data, value, percent, start, end, selected, plus cursor x/y when the browser event provides them.

Use events: [] to disable forwarding, or events: :all for every name in ECharts.Events.all/0.

7. Static pages

For controller-rendered pages, use static_echarts/2:

# controller
def index(conn, _params) do
  chart = ECharts.Express.bar(data, x: "month", y: "sales")
  render(conn, :index, chart: chart)
end
<%# template %>
<%= ECharts.Phoenix.Component.static_echarts(@chart, id: "sales") %>

The static renderer scans the page on load and observes DOM insertions, so charts added later still mount. It requires the asset plug.

8. Themes

chart = ECharts.new(option, theme: :dark)
chart = ECharts.new(option, theme: ECharts.Theme.dark())

theme: :dark selects the built-in ECharts dark theme. A theme map from ECharts.Theme.dark/0 gives you a palette that matches the rest of your UI.

To follow a light/dark toggle, rebuild the chart with the selected theme and reassign it (or push it with push_update/3).

Troubleshooting

Blank container. The hook is not registered. Check that EChartsHook is in the hooks map passed to LiveSocket, and that the container has phx-hook="EChartsHook" (the component adds it).

404 for /echarts/echarts.min.js. The plug is not mounted. Add forward "/echarts", ECharts.Phoenix.Plug to the router before the LiveView routes, or accept the jsDelivr fallback.

Charts update but the canvas disappears. The chart is being re-created inside a stream or a phx-update container. Keep the chart element stable and use push_update/3 for frequent updates.

3D charts are blank. Pass gl: true and use a browser with WebGL enabled. ECharts GL requires the canvas renderer.

CSP blocks the bundle. Serve the assets with the plug and allow the /echarts path in your script-src directive. The hook uses classic script loading (no inline script) for the bundle.

Next