How to Use JavaScript in a Phoenix LiveView: Difference between revisions
From ElixirBlocks
No edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
You can integrate JavaScript libraries with Phoenix LiveView. | 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. | ||
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. | |||
<source> | <source> |
Revision as of 07:29, 2 April 2023
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 the function 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 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" } } } })