Alpine.js
01 / 02

Directives & Reactivity

Directives & Reactivity

No Build Step Needed

<script src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js" defer></script>

<!-- That's it — no webpack, no compile step, works directly in the HTML -->
<div x-data="{ open: false }">
  <button @click="open = !open">Toggle</button>
  <div x-show="open" x-transition>Content</div>
</div>

Core Directives

<div x-data="{ search: '', items: ['Apple', 'Banana', 'Cherry'] }">
  <input x-model="search" placeholder="Search..." />
  <p x-text="`Searching for: ${search}`"></p>

  <ul>
    <template x-for="item in items.filter(i => i.toLowerCase().includes(search.toLowerCase()))" :key="item">
      <li x-text="item"></li>
    </template>
  </ul>

  <button :class="search ? 'text-blue-500' : 'text-gray-400'">Filter active</button>
</div>

<!-- x-show toggles CSS display, keeps the element in the DOM;
     x-if (on a <template>) actually adds/removes it entirely -->

Initialization & Avoiding Flash of Unstyled Content

<style>[x-cloak] { display: none; }</style>

<div x-data="{ open: false }" x-init="open = localStorage.getItem('panelOpen') === 'true'" x-cloak>
  <div x-show="open">Panel content</div>
</div>
<!-- x-cloak hides the element until Alpine finishes initializing, avoiding
     a brief flash of un-initialized markup before directives take effect -->

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free