x-ref Directive

Store a reference to a DOM element – access it later with $refs.

What is x-ref?

x-ref stores a reference to a DOM element. You can access it later via the $refs magic property. It's essentially Alpine's way of giving you direct access to DOM nodes.

When to Use

Use x-ref when you need direct access to a DOM element for operations like focusing an input, reading a canvas, measuring dimensions, or integrating with vanilla JS libraries.

Example

Code
<div x-data>
  <input x-ref="myInput" type="text">
  <button @click="$refs.myInput.focus()">Focus input</button>
</div>

$refs is an object whose keys are the names given to x-ref. You can have as many refs as you need.

Helpful? Share this page!↑ Back to top