Skip to content

Comments

Fix x-ref crash during morph operations#4744

Closed
MichaelWest22 wants to merge 3 commits intoalpinejs:mainfrom
MichaelWest22:x-ref-no-root-guard
Closed

Fix x-ref crash during morph operations#4744
MichaelWest22 wants to merge 3 commits intoalpinejs:mainfrom
MichaelWest22:x-ref-no-root-guard

Conversation

@MichaelWest22
Copy link

Fix x-ref crash during morph operations

Problem

When morphing a child element (not the root x-data element), Alpine crashes if that element contains x-ref attributes. This breaks both Alpine's morph plugin and htmx's Alpine compatibility.

The crash happens because morph creates temporary DOM fragments to prepare the new HTML. When Alpine initializes x-ref on elements in these fragments, closestRoot() returns null since there's no x-data ancestor yet. The code then tries to access root._x_refs, causing a null reference error.

Solution

Added a simple guard to return early when no root is found:

if (! root) return

This lets x-ref gracefully skip initialization during the fragment preparation phase. Once the element is inserted into the actual DOM tree, Alpine properly initializes the ref with the correct root.

Test

Added test case that morphs a child element containing x-ref to verify:

  • Morph completes without errors
  • State is preserved
  • $refs still works after morph

@calebporzio
Copy link
Collaborator

chose alternative solution in #4748 - thanks! fixed up now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants