$refs Magic Property

Access elements marked with x-ref – an object of DOM nodes.

What is $refs?

$refs is a magic object containing references to all elements that have an x-ref attribute inside the current component. Each key corresponds to the ref name and holds the actual DOM node.

When to Use

Use $refs whenever you need direct access to a specific child element – focusing an input, reading a canvas context, measuring an element's size, or integrating with a vanilla JS library.

Basic Example

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

Multiple Refs

You can have as many refs as you like, and they are all available in the $refs object.

Code
<div x-data>
  <canvas x-ref="canvas"></canvas>
  <input x-ref="searchBox" placeholder="Search">
  <button @click="
    $refs.searchBox.focus();
    console.log($refs.canvas.getContext('2d'))
  ">Activate</button>
</div>

💡 Tip

Ref names must be unique within a component. If you have multiple elements with the same ref name, only the last one will be stored.

⚠️ Warning

Don't rely on $refs being available immediately in x-init if the ref is inside a x-if or x-for that hasn't rendered yet. Use $nextTick to wait for the DOM.

Can I use $refs on components defined with Alpine.data()?

Yes, $refs works exactly the same way inside any Alpine component, regardless of how the data is defined.

Helpful? Share this page!↑ Back to top