You often face situations when you need to bind dynamic data with attributes. Alpine JS x-bind
directive helps you add dynamic classes, styles, and many other attributes. First, let’s learn what’s the shorthand syntax of x-bind
.
x-bind Shorthand Syntax in Alpine JS
Check the following code that does the same thing with a complete syntax of x-bind
and shorthand syntax of x-bind
.
The complete syntax of x-bind
in Alpine JS.
1 2 3 4 5 6 7 |
<div x-data="{ placeholder: 'Search...' }"> <input type="text" x-bind:placeholder="placeholder"> </div> |
Shorthand syntax of x-bind
in Alpine JS.
1 2 3 4 5 6 7 |
<div x-data="{ placeholder: 'Search...' }"> <input type="text" :placeholder="placeholder"> </div> |
Using x-bind
to Add classes
You can add conditional classes in Alpine JS with the help of x-bind
. The following example adds a class based on the open attribute in x-data
.
1 2 3 4 5 6 7 8 9 |
<h1 class="text-2xl font-bold" :class=" { 'bg-green-500': open }" > TailwindCSS with Alpine JS </h1> |
Using x-bind
with Styles in Alpine JS
You can also use x-bind
complete or shorthand syntax to bind custom styles. The following example adds to style properties with x-bind
. You just need to make sure you pass an object with camel case properties.
1 2 3 4 5 6 7 8 9 |
<div x-data> <h1 :style="{ color: 'red', textAlign:'center' }"> Applying conditional styles </h1> </div> |
Conditionally bind Custom Styles with x-bind
You can also add styles based on a condition with x-bind
shorthand syntax. The following example explains how to bind styles on a condition. When the user clicks on the button, the loggedIn state becomes true and the styles are applied.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<div x-data="{loggedIn:false}"> <h1 :style="loggedIn && { color: 'blue', fontSize:'40px'}"> Applying conditional styles </h1> <div class="flex justify-center"> <button @click="loggedIn=true" class="rounded-lg bg-blue-500 px-5 py-2 text-white" > Click to Change styles </button> </div> </div> |
Conclusion
Alpine JS x-bind
directive helps to dynamically add attribute values. The above examples cover almost all the use cases with shorthand syntax. If you want to read more about x-bind
, please check the official documentation on the Alpine JS website.