Adding phx-target={@myself} to a function component to make it usable in either a liveview or a liveview component

I have a form currently defined as a function component used in a liveview. Now the same form is needed in one of my liveview components (as opposed to a function component). Simply using the function component here doesn’t work because the phx-click event is sent to the parent liveview instead of the component itself (@myself).

I thought defining an attr like this might work as myself is defaulted to nil and ignored, unless the function component is inside a liveview component where myself points to the component properly.

attr :myself, :any, default: nil
def function_component(assigns) do
~H """
...
 <button phx-click="handle_me" phx-target={@myself} > ...
...
"""
```
But this results in an error that complains myself is not in assigns.

Is there a way to make this work without converting the function component to a liveview component? I want to avoid that if possible.

Thanks.

Are you calling <.function_component myself={@myself}>? A function component won’t implicitly “inherit” @myself.

Just as a point of style, a clearer name would be @target or @button_target.

4 Likes

That was it. Thank you!!

1 Like