Adding new LiveView component ignores AlpineJS directives

So I figured where the problem is how to solve it. When a new element (component) is added to the page the onBeforeElUpdated is not called and therefore all Alpine directives are not initialized.

To properly wire up Alpine for newly added DOM components make sure to add this callback to your socket config.

  dom: {
    // add this callback
    onNodeAdded(node) {
      if (node._x_dataStack) {
        window.Alpine.initTree(node);
      }
    },
    onBeforeElUpdated(from, to) {
      if (from._x_dataStack) {
        window.Alpine.clone(from, to);
        window.Alpine.initTree(to);
      }
    },
  }

Hope this helps someone in the same situation :slightly_smiling_face:

9 Likes