When to use phx-click vs JS.push?

I have a <button> in my heex template.

It seems like I can use both phx-click and JS.push interchangeably?

I’ve been using JS.push primarily since it seems more in-tune with what’s actually happening right? I’m pushing an event to my liveview using JS on the frontend.

phx-click={JS.push("save_rating", value: %{rating: 4})}

Yes you can.

I use the JS command when I need to run another JS command that will do something else that doesn’t need to go to the server AND push an event so I can pipe them.

phx-click={JS.hide(transition: "fade-out", to: "#modal") |> JS.push("save_rating", value: %{rating: 4})}

If I only need to send the event, I prefer using the phx- bindings. This approach also makes it easier to test because you can select elements based on their events, if you use the JS commands you need to work around this limitation.

# element:
<button type="button" id="button-to-test" phx-click={JS.push("save_rating", value: %{rating: 4})}>Button</button>

# test:
view
  |> element("button[id=button-to-test]", "Button")
  |> render_click()

# element:
<button type="button" phx-click="save_rating" phx-value-rating="4">Button</button>

# test:
view
  |> element("button[phx-click='save_rating'][phx-value-rating='4']", "Button")
  |> render_click()
4 Likes

Nice that’s a great tip thanks for sharing dude!

1 Like