Alpine version 3." /> Alpine version 3." /> Alpine version 3."/>

Adding x-ref to an element results in Uncaught TypeError: root is undefined on page load

16 Views Asked by At

When adding x-ref like this to a div and loading the page, I get an Uncaught TypeError: root is undefined.

<div x-ref="commandview">

Alpine version 3.13.5.

That's the line in question:

// packages/alpinejs/src/directives/x-ref.js
  function handler3() {
  }
  handler3.inline = (el, { expression }, { cleanup: cleanup2 }) => {
    let root = closestRoot(el);
    if (!root._x_refs) // error happens here
      root._x_refs = {};
    root._x_refs[expression] = el;
    cleanup2(() => delete root._x_refs[expression]);
  };
  directive("ref", handler3);
1

There are 1 best solutions below

0
Alexander Zeitler On BEST ANSWER

Just found this issue comment on GitHub:

... It seems like Alpine assumes that if x-ref is used then an x-data must be in a parent element. ...

By adding x-data like this to an parent element of the div I got it to work as expected:

<div x-data>
  <div x-ref="commandview"></div>
</div>