Alpine js cheat sheet pdf download

Alpine JS cheat sheet | PDF download

You will get the Alpine JS complete cheat sheet with a PDF file in this tutorial.

Why Alpine JS?

Alpine.js provides the reactive and declarative features of large frameworks such as Vue or React in a very simple approach.

Alpine.js is small (7kB gzip) and designed for writing markup-driven client-side JavaScript.

The syntax is similar to Vue and the Angular directive.

The rise of utility-based solutions such as Tailwind CSS has recently done an amazing job with CSS, while Alpine.js promises something similar for JavaScript.

Let’s see an example, display the current year in the footer. It doesn’t require adding an additional JavaScript file. You can do almost everything while staying on the same page.

This Alpine JS cheat sheet will help you to look at the syntax quickly while coding.

Installation of Alpine.js

Install using CDN or use it as an npm module

npm install alpinejs

Import in your JavaScript File

import Alpine from 'alpinejs'
 
window.Alpine = Alpine
 
Alpine.start()

Alpine.js attributes

There are currently 15 attributes available.

  1. x-data
  2. x-init
  3. x-show
  4. x-bind & x-bind class
  5. x-text
  6. x-html
  7. x-if
  8. x-for
  9. x-on & x-on modifiers
  10. x-model & x-model modifiers
  11. x-ref
  12. x-effect
  13. x-transition
  14. x-cloak
  15. x-ignore

x-data

In Alpine, everything begins with the x-data directive. x-data specifies a block of HTML as an Alpine component. It provides reactive data for that component to use.

<div x-data="{ isValid: false }">
    <!-- isValid is available only in this block -->
</div>

All element children have access to the properties defined in a x-data directive. Even the nested x-data components.

<div x-data="{ isValid: 'Yes' }">
    <span x-text="isValid">
        <!-- "Yes" -->
    </span>

    <div x-data="{ isSet: 'No' }">
        <span x-text="isValid">
            <!-- "Yes" -->
        </span>

        <div x-data="{ isValid: 'No' }">
            <span x-text="isValid">
                <!-- "No" -->
            </span>
        </div>
    </div>
</div>

Methods defined in x-data

You may define the methods with different properties in the x-data object.

<div x-data="{ 
           open: false, 
           toggle() { 
             this.open = ! this.open 
            } 
         }">

    <button @click="toggle()">Click To Toggle The Content</button>
    <div x-show="open">
        Toggle The Content...
    </div>
</div>

x-init

The x-init directive allows you to intercept the initialization step of any Alpine element.

<div x-init="console.log('page loading begins')"></div>

In the preceding example, “page loading begins” will be output in the console before any more DOM updates are made.

You may also use it to fetch some JSON and store it in x-data before the component is processed.

<div
    x-data="{ users: [] }"
    x-init="users = await (await fetch('/api/users')).json()"
>

<!--  your logic here  -->

</div>

It is standalone. You can include x-init in any element within or outside of an x-data HTML block. As an example:

<div x-data>
 <div x-init="console.log('component initialize here')"></div>
</div>
     
<div x-init="console.log('component initialize here too')"></div>

Evaluate the init() method automatically

If a component’s x-data object contains an init() method, it will be called automatically. As an example:

<div x-data="{
    init() {
        console.log('init method called automatically')
    }
}">

<!--  your logic here  -->

</div>

x-show

It allows you to show and hide DOM elements in an effective manner.

<div x-data="{ showElement: true }">
  <div x-show="showElement">
    This is visible...
  </div>
</div>


<div x-data="{ showElement: false }">
  <div x-show="showElement">
    This is hidden...
  </div>
</div>

v-bind

You can use x-bind to set HTML attributes on elements. for example class, id, placeholder, etc.

<div x-data="{ placeholder: 'Input email' }">
  <input type="email" x-bind:placeholder="placeholder">
</div>

You may use the shorthand syntax with colons (:) and avoid the v-bind syntax for simplicity.

<input type="email" :placeholder="placeholder">

This is useful for binding classes.

<div :class="{ 'hidden': ! show }">

x-on

x-on is used to listen to events.

<button x-on:click="alert('Hello World!')">Say Hi</button>

You may use the shorthand syntax: @

<button @click="alert('Hello World!')">Say Hi</button>

x-text

x-text sets the text content of an element. It works similarly to JavaScript innerText.

 <div x-data="{ firstName: 'John', lastName:'Doe' }">

   <div>First Name: <strong x-text="firstName"></strong></div>

   <div>Last Name: <strong x-text="lastName"></strong></div>

</div>

x-html

The innerHTML property of an element is set by x-html.

<div x-data="{ firstName: '<strong>John</strong>' }">

  <div>First Name: <span x-html='firstName'></span></div>

</div>

x-if

x-if add or remove a piece of HTML block conditionally. Unlike x-show the x-if removes the block of HTML completely. This attribute usually works with <template> a tag.

<template x-if="open">
  <div>This block is visible if 'open' is equal to true.</div>
</template>

x-model

The x-model allows you to bind an input element’s value to Alpine data.

Here’s an example of how to use x-model in Alpine to connect the value of a text field to Alpine data.

<div x-data="{ message: '' }">
    <input type="text" x-model="message">
    <span x-text="message">
</div>

The x-model is used for two-way binding, which means it “sets” as well as “gets” data. It not only changes the data, but it also reflects the change anytime the data changes.

<textarea x-model="message"></textarea>
 
<span x-text="message"></span>

In the same way, you may use it with all kinds of HTML input elements. For details read the documentation about x-model.

x-ref

The x-ref is used to access any element directly. It works similarly to getElementById and querySelector in Javascript.

For example, we will access the <span> tag.

<span x-ref="text" id="span-tag">Hello 👋</span>

In simple javascript, we can use getElementById like:

getElementById('span-tag')

In Alpine JS we can access the tag with $refs:

<button @click="$refs.text.remove()">Remove Text</button>

x-effect

This directive can be used to update an expression whenever one of its dependencies changes. It continuously watches the changes in its dependencies and runs whenever a change occurs.

For example, look at the following code. The x-effect is watching label_1 only. You will see the output when label_1 changes.

    <div
      x-data="{ label_1: 'Hello', label_2:1 }"
      x-effect="console.log(label_1)"
    >
      <button @click="label_1 += ' World!'">Change label_1</button>
      <button @click="label_2 += 1">Change label_2</button>
    </div>

x-ignore

x-ignore is used to simply ignore the element. for example, in the following case the ‘Text on Label’ will not appear in the <span> tag because we are using x-ignore to ignore the contents of the div completely.

<div x-data="{ label: 'Text on Label' }">
    <div x-ignore>
        <span x-text="label"></span>
    </div>
</div>

x-for

The x-for directive lets you iterate through a list to produce DOM elements. Here’s a simple example of how to use it to generate a color list from an array.

<ul x-data="{ colors: ['Red', 'Orange', 'Yellow'] }">
    <template x-for="color in colors">
        <li x-text="color"></li>
    </template>
</ul>

Specify unique keys for each x-for iteration

<ul x-data="{ colors: [
    { id: 1, name: 'red' },
    { id: 2, name: 'blue' },
    { id: 3, name: 'green' },
]}">
    <template x-for="color in colors" :key="color.id">
        <li x-text="color.name"></li>
    </template>
</ul>

Accessing indexes in x-for

If you need to get the index of each item in the iteration, use the ([item], [index]) syntax in [items] as follows:

<ul x-data="{ colors: ['Red', 'Orange', 'Yellow'] }">
      <template x-for="(color, index) in colors">
        <li>
             <span x-text="index + ': '"></span>
             <span x-text="color"></span>
        </li>
      </template>
</ul>

Iterating over a range in x-for

Alpine provides a concise syntax for looping n number of times.

<ul>
    <template x-for="i in 6">
        <li x-text="i"></li>
    </template>
</ul>

x-transition

You may make seamless transitions between when an element is visible and when it is hidden using x-transition directives.

<div x-data="{ open: false }">
    <button @click="open = ! open">Toggle</button>
 
    <span x-show="open" x-transition>
        Hello 👋
    </span>
</div>

Customizing duration with x-transition

With the .duration modifier, you may specify the duration of a transition:

<div ... x-transition.duration.500ms>

The default duration is 150 milliseconds when entering, and 75 milliseconds when leaving.

If you want to customize the durations for leaving and entering, do so as follows:

<div ...
    x-transition:enter.duration.600ms
    x-transition:leave.duration.500ms
>

Delay the transition

You may use the .delay modifier to delay a transition as follows:

<div ... x-transition.delay.50ms>

x-cloak

Suppose you are adding a modal and only want to show it conditionally. The modal sometimes appears as the page loads and then suddenly disappears once Alpine Js loads.

This situation is addressed by x-cloak , hiding the element it is attached to until Alpine completely loads.

Once Alpine js loads it removes x-cloak from elements. It is used to hide the elements in conjunction with CSS rules like

[x-cloak] {display: none}