How to Use JavaScript in a Phoenix LiveView

From ElixirBlocks
Revision as of 07:30, 2 April 2023 by Admin (talk | contribs)
Jump to: navigation, search

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 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"
			}
		}
	}
})