live_props v0.2.2 LiveProps.LiveComponent View Source
When you use LiveProps.LiveComponent
in your Phoenix LiveComponent, all of the functionality
in LiveProps.Props
and LiveProps.States
will be imported.
Example
defmodule ButtonComponent do
use Phoenix.LiveComponent
use LiveProps.LiveComponent
prop :class, :string, default: "button"
prop :text, :string, default: "Click me"
prop :on_click, :string, default: "click_button"
def render(assigns) do
~L"""
<button class="<%= @button %>"
phx-click="<%= @on_click %>">
<%= @text %>
</button>
"""
end
In this example we define three props that will be automatically assigned default values, so you don't have to define your own mount or update callbacks to do it yourself.
More examples can be found in the LiveProps
documentation.
Component Lifecycle
A Phoenix LiveComponent defines several callbacks, such as mount/1
, preload/1
, and update/2
.
LiveProps injects these callbacks under the hood so you don't have to (but you can if you want).
If you do not define your own callbacks, the injected ones will be executed as follows:
mount/1 ---> update/2
(default and computed (default and computed props
states assigned) merged/assigned)
States and props will always be assigned in the order defined.
If you do define a mount or update callback, they will be run after the associated callback injected by LiveProps. In other words, in your mount/1 callback, default and calculated states will already be assigned to the socket. In your update/2 callback, default and computed props will have been assigned too.
If you define a c.Phoenix.LiveComponent.preload/1
callback, which takes a list of assigns,
default and computed props will be available in all assigns.
Pitfalls
If you try to pass a value to a LiveProps.LiveComponent and it has been declared
in that component as a state, it will be ignored. (i.e. will not be assigned to the socket). State
is meant only to be set within the socket or using LiveProps.States.send_state/3
from a LiveView
or another componenet. (You must use LiveProps.States.send_state/3
rather
than Phoenix.LiveView.send_update/2
)