How to Use JavaScript in a Phoenix LiveView
From ElixirBlocks
You can integrate JavaScript libraries with Phoenix LiveView.
The first step is to create a LiveView. In the render method of the LiveView, you create a DOM element that has an assigned phx-hook property.
defmodule AppWeb.PageLive do use AppWeb, :live_view def mount(_params, _session, socket) do {:ok, socket} end def render(assigns) do ~H""" <div id="boxer" phx-hook = "Boxer">BOXER TEXT</div> """ end end
In assets/js/app.js you will see this code:
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
You change the function to use a "hooks" property as in the example below. The hooks property is assigned the name of the phx-hook value. A mounted method is part of the api and is used below. The this keyword is used to select the element.
Example
let liveSocket = new LiveSocket("/live", Socket, { params: {_csrf_token: csrfToken}, hooks:{ Box:{ mounted(){ this.el.textContent = "Hello World" } } } })