How to Use JavaScript in a Phoenix LiveView: Difference between revisions
From ElixirBlocks
								
												
				|  (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...") | No edit summary | ||
| Line 3: | Line 3: | ||
| The first step is to create a 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. | |||
| <source> | <source> | ||
Revision as of 07:26, 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 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"
			}
		}
	}
})