Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

What is Alpine.js

Alpine.js is a small library that adds interactivity right in your HTML. Behavior is described with tag attributes: x-data holds data, x-on reacts to events, x-show hides and shows elements. You do not need a build step or component files — one script is enough. This course covers Alpine.js 3.

A first example

Here is a complete counter. The Alpine script is loaded with a <script> tag that has the defer attribute:

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
 
<div x-data="{ count: 0 }">
  <button x-on:click="count++">Click</button>
  <span x-text="count"></span>
</div>

Below the example you see a button and a number. Every click increases count, and Alpine updates the text in the <span> by itself. You did not write a single querySelector or addEventListener call.

Directives

Attributes that start with x- are called directives. Each directive does one job:

DirectiveWhat it does
x-dataDeclares a component and its data
x-textOutputs a value as text
x-onListens to an event
x-showShows or hides an element
x-forRepeats an element for each array item
x-modelBinds a form field to data

A directive's value is a regular JavaScript expression that can see the data of its component.

When to choose Alpine

React and Vue build the whole page out of components and usually need a build step. Alpine works on top of ready HTML that came from the server. That makes it a good fit where the backend renders pages — Laravel, Symfony, Django, Rails — and the page needs dropdown menus, tabs, modals or filters.

Alpine is especially popular with Laravel developers: Livewire's interactive features are built on it, and Livewire 3 includes Alpine automatically.

For a large single-page app with client-side routing, React or Vue is a better choice.

What the course covers

The running example is a to-do list: adding tasks, marking them done, filtering, saving. The lessons on common UI pieces add a dropdown menu, tabs and a modal. Every example with a <script> tag works right on the lesson page — click the buttons and change the code in the sandbox.

Common mistake

Using a directive outside a component. Directives only work inside an element with x-data or on that element itself:

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
 
<div x-data="{ name: 'Anna' }"></div>
<p x-text="name"></p>

Here the <p> sits next to the component, not inside it, so it stays empty: Alpine processes only elements inside components and silently skips the rest, without even an error in the console. Move the <p> inside the <div>.

Thanks for reading!

Donate to the site — we work hard for you.