How to Use JavaScript in a Phoenix LiveView: Difference between revisions
No edit summary |
No edit summary |
||
Line 16: | Line 16: | ||
~H""" | ~H""" | ||
<div id=" | <div id="box" phx-hook = "Box">BOX TEXT</div> | ||
Revision as of 19:26, 2 April 2023
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="box" phx-hook = "Box">BOX TEXT</div> """ end end
JavaScript Hooks
To connect your JavaScript code you need to create a JavaScript Hook. The following instructions show you what a hook is and how to create one using the previous LiveView code.
In assets/js/app.js you will see a LiveView constructor function.
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
Update the code to use a hooks property per the example below. Take notice that after the hooks property a property that has the same name as the phx-hook property (in this case Box) is set. You then set a mounted method and inside it you write DOM code to manipulate the element in the LiveView.
Example
let liveSocket = new LiveSocket("/live", Socket, { params: {_csrf_token: csrfToken}, hooks:{ Box:{ mounted(){ this.el.textContent = "Hello World" } } } })