How to Use JavaScript in a Phoenix LiveView

From ElixirBlocks
Revision as of 07:25, 2 April 2023 by Admin (talk | contribs) (Created page with "You can integrate JavaScript libraries with Phoenix LiveView. The first step is to create a LiveView. The Next Step is to create a DOM element that has an assigned phx-hook property. <source> <div id="box" phx-hook = "Box">SOME TEXT</div> </source> In <pre>assets/js/app.js </pre> you will see this code: <source> let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}}) </source> You change it to use a "hooks" property, the hooks...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

You can integrate JavaScript libraries with Phoenix LiveView.

The first step is to create a 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"
			}
		}
	}
})