Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a warning to the JS Hook documentation for changing phx-hook #3509

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions guides/client/js-interop.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,34 @@ let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks, ...})

*Note*: when using `phx-hook`, a unique DOM ID must always be set.

> #### Warning {: .warning}
>
> Hooks cannot be added dynamically on an element. For example:
> ```heex
> <div id="my-hook" phx-hook={if @hook_enabled, do: "MyHook"} />
> ```
>
> In this case, if `@hook_enabled` starts as `true`, then the hook will work as
> intended. However, if the value starts as `false` and changes from `false` to `true`,
> the hook will never be initialized, and therefore `mounted` will never be called.
>
> To achieve the desired effect, the hook should always be set, and an attribute on
> the DOM element can be checked in the `updated` callback to toggle the state of
> the hook.
>
> ```heex
> <div id="my-hook" phx-hook="MyHook" data-hook-enabled={to_string(@hook_enabled)} />
> ```
> ```javascript
> hooks.MyHook = {
> updated: {
> if (this.el.getAttribute("data-hook-enabled") !== "false")) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
> if (this.el.getAttribute("data-hook-enabled") !== "false")) {
> if (this.el.dataset.hookEnabled !== "false") {

> this.el.innerHTML = "MyHook is enabled";
> }
> }
> }
> ```

For integration with client-side libraries which require a broader access to full
DOM management, the `LiveSocket` constructor accepts a `dom` option with an
`onBeforeElUpdated` callback. The `fromEl` and `toEl` DOM nodes are passed to the
Expand Down
Loading