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 LiveView, the next Step is to create a DOM element that has an assigned phx-hook property.
<div id="box" phx-hook = "Box">SOME TEXT</div>
In
assets/js/app.js
you will see this code:
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
You change it to use a "hooks" property, the hooks property is assigned the name of the phx-hooks value. A mounted method is part of the api and is assigned 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" } } } })