How to Use bind (x-bind) with Classes in AlpineJS

In this Alpine.js tutorial, we will explore the usage of x-bind for binding classes, styles, and images. x-bind functions similarly to Vue.js’s v-bind directive. If you’re familiar with Vue.js, understanding x-bind will be straightforward. It enables you to set HTML attributes on elements based on the result of JavaScript expressions. You can use x-bind to bind classes, apply special CSS behaviors, and bind styles. Additionally, you can utilize it to bind images dynamically.

Syntax

we will use x-bind to set the age value of an input value and class like x-bind:class , x-bind:value.

<div x-data="{ age: 18, bigText:'text-2xl font-bold' }">
    <label for="age" x-bind:class="bigText">Age</label>
    <input type="text" name="age" x-bind:value="age" class="w-full p-2 border border-gray-300 focus:outline-none "
        placeholder="Enter Your Age">
</div>
use x-bind) with Classes

Shorthand syntax

we can also use x-bind:class , x-bind:value to :class or :value to short code.

<div x-data="{ age: 18, bigText:'text-2xl font-bold' }">
    <label for="age" :class="bigText">Age</label>
    <input type="text" name="age" :value="age" class="w-full p-2 border border-gray-300 focus:outline-none "
        placeholder="Enter Your Age">
</div>

Example 1

Binding with Classes. You can write short class code using x-bind to classes.

<div x-data="{ inputClass: 'w-full p-2 border border-gray-300 focus:outline-none' }" class="space-y-2">
    <input type="text" :class="inputClass" name="name" placeholder="Name">
    <input type="text" :class="inputClass" name="email" placeholder="Email">
    <input type="text" :class="inputClass" name="age" placeholder="Age">
</div>
x-bind with class

Example 2

Binding with Style.

<div x-data="{ styles: { background: 'blue', width:200, height:200, padding:'4rem'}}">
    <div :style="styles">
        Style Binding
    </div>
</div>
style binding

Example 3

Binding with Image. you can use this methods alpine v3.

<div x-data="{ image: 'https://picsum.photos/200/300?grayscale' }">
    <img :src="image" alt="image">
</div>
Binding with Image

You can use like this.

<div x-data="myImage">
    <img :src="image" alt="image">
</div>
<script>
    document.addEventListener('alpine:init', () => {
        Alpine.data('myImage', () => ({
            image: "https://picsum.photos/200/300?grayscale"
        }))
    })
</script>

Example 4

you can also bind in condition like ternary and or with classes. you can write short class code using x-bind.

<div x-data="{ isOpen: false }">
    <button @:click="isOpen = ! isOpen"> Dropdown</button>
    <div :class="isOpen ? '' : 'hidden'">
        Dropdown content...
    </div>
</div>

To better using x-show.

<div x-data="{ isOpen: false }">
    <button x-on:click="isOpen = ! isOpen"> Dropdown</button>
    <div x-show="isOpen">
        Dropdown content...
    </div>
</div>