How to Use JavaScript in a Phoenix LiveView: Difference between revisions

From ElixirBlocks
Jump to: navigation, search
No edit summary
No edit summary
Line 30: Line 30:
==JavaScript Hooks==
==JavaScript Hooks==


To connect your JavaScript code you need to create a JavaScript Hook. The following instructions show you what is a hook is and how to create one using the previous LiveView code.
To connect your JavaScript code you need to create a JavaScript Hook. The following instructions show you what a hook is and how to create one using the previous LiveView code.


In '''assets/js/app.js'''  you will see this code:
In '''assets/js/app.js'''  you will see a LiveView constructor function.


<source>
<source>
Line 41: Line 41:




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.
Update the code to use a hooks property per the example below. Take notice that after the hooks property a property that has the same name as the phx-hook property (in this case Box) is set. You then set a mounted method and inside it you write DOM code to manipulate the element in the LiveView.
 
 


'''Example'''
'''Example'''

Revision as of 19:26, 2 April 2023

You can integrate JavaScript libraries with Phoenix LiveView.


The first step is to create a LiveView. In the render method of the LiveView, you create a DOM element that has an assigned phx-hook property.


defmodule AppWeb.PageLive do
  use AppWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok, socket}
  end

  def render(assigns) do
    ~H"""
 
       <div id="boxer" phx-hook = "Boxer">BOXER TEXT</div>


    """
  end
end



JavaScript Hooks

To connect your JavaScript code you need to create a JavaScript Hook. The following instructions show you what a hook is and how to create one using the previous LiveView code.

In assets/js/app.js you will see a LiveView constructor function.

let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})


Update the code to use a hooks property per the example below. Take notice that after the hooks property a property that has the same name as the phx-hook property (in this case Box) is set. You then set a mounted method and inside it you write DOM code to manipulate the element in the LiveView.


Example


let liveSocket = new LiveSocket("/live", Socket, {

	params: {_csrf_token: csrfToken},
	hooks:{
		Box:{
		 mounted(){
                    this.el.textContent = "Hello World"
			}
		}
	}
})