#Phoenix Component click event vs Live Component click event

4 messages · Page 1 of 1 (latest)

steel pine
#

With a Live Component (https://hexdocs.pm/phoenix_live_view/Phoenix.LiveComponent.html), the phx-click events it triggers a handle_event so you can easily elixir functions elsewhere, but when looking at the Phoenix Component (https://hexdocs.pm/phoenix_live_view/Phoenix.Component.html), I am a little confused about what phx-click event does/how to use it.

I can see in the core_components.ex it's used to run some JavaScript - but was wondering if that was all?

For example if I wanted to navigate from a phoenix component to a liveview component, is that something I could do with phx-click? Or would it be wrong to use a phx-click for navigation and I should use <.link navigate={...} /> instead?

Essentially I'm looking for a way to do the below but with a function component on a div

  def handle_event("view_server", params, socket) do
    {:noreply, push_redirect(socket, to: "/server/#{params["id"]}")}
  end
steel pine
#

Sat on it for a bit and used my brain for a hot second, have progressed to this where the phx-click calls a function - but this only runs the function when the page is loaded and not on click.

Anyone have any ideas why it could be doing this?

defmodule ExampleWeb.ServerComponent do
  use Phoenix.Component

  def view_server(id) do # this gets called on page load, does nothing on click
    IO.inspect("Clicked")
  end

  def component(assigns) do
    ~H"""
      <div phx-click={view_server(@server.id)}>Server</div>
    """
  end
end
lone forge
#

unlike react, you just send a message and payload when trying to do phx-click.

You can handle that click in handle_event function.

#

There are two ways to go about phx-click -

  1. normal messages to the server via phx-click="eventname" or JS.push
  2. Using purely client side show/hide / css stuff.

see examples here.
https://github.com/fly-apps/live_beats/blob/712204ca172ed6d36456c8ed4fd6aaba50099447/lib/live_beats_web/live/profile_live.ex#L29

https://github.com/fly-apps/live_beats/blob/712204ca172ed6d36456c8ed4fd6aaba50099447/lib/live_beats_web/live/player_live.ex#L60

GitHub

Contribute to fly-apps/live_beats development by creating an account on GitHub.

GitHub

Contribute to fly-apps/live_beats development by creating an account on GitHub.