In this episode, we're taking a look at refs in Alpine.js. Refs are simply a way to directly reference (or "pinpoint") any element in your component, making it super easy to interact with specific pieces of your template from your JavaScript.
To make things practical—and a bit more fun—we walk through building a simple image file chooser. We'll set up a form with a native HTML file input, and when a user selects an image, we'll show a live preview before anything gets uploaded. This is especially handy for things like updating avatars or profile pictures.
First, we show how you could use a plain old document.getElementById
, but that's a bit clunky. Instead, Alpine's x-ref
directive lets you give any element a custom name, and access it through Alpine's refs
object. You can have as many refs as you want, making your component much more organized and flexible.
We also cover scenarios like auto-focusing an input field in a modal, which is just one of countless real-life uses for refs. Then, in our file input, we watch for the change
event, grab the selected file, use the FileReader API to read it as a data URL, and render out a preview image on the page. It's a nice demonstration of how Alpine can sprinkle interactive features over a normal HTML form without completely taking over.
By the end of the lesson, you'll see how easy it is to add interactivity like image previews using refs, without a bunch of messy IDs or global DOM queries. So, that's Alpine refs in action—simple, powerful, and a great addition to your toolkit!