Learn how to use x-data in AlpineJS

In this Alpine.js tutorial, we’ll explore x-data. The x-data directive declares a new component scope, instructing the framework to initialize a new component with the data object. Alpine.js begins with x-data. Let’s delve into some Alpine.js examples.

Example 1

First, we need to create x-data in a div or any HTML tag to start Alpine.js components. Then, we can define an object like JavaScript and assign values to the object. To display the object, we use x-text, which will print the output.

<div x-data="{message: 'Alpine js is Awesome'}">
      <p x-text="message"></p>
</div>

You can use other HTML tags; it works with all of them. You can use div, h1, p, ul, or any other tag, and it will work. However, for the right way, you should use x-data with the div tag; it is the preferred method.

<h1 x-data="{hOne: 'h1 one is working'}" x-text="hOne"></h1>
<p x-data="{pTag: 'p tag is working'}" x-text="pTag"></p

Example 3

Don’t Do

You should not print outside of div tag x-data start with open close tags if you call outside of tag it will not work.

<div x-data="{message: 'Alpine js is Awesome'}">
    <h2>Apline js</h2>
</div>
<p x-text="message"></p>

Do

<div x-data="{message: 'Alpine js is Awesome'}">
    <h2>Apline js</h2>
    <p x-text="message"></p>
</div>

Example 4

if you have many filed you can display like 👇 this . or you can display better way.

To Do This 👇

<div x-data="{ 
    name: 'larainfo',
    email:'[email protected]',
    number : 99999999,
    pincode:666656 
}">
    <ul>
        <li x-text="name"></li>
        <li x-text="email"></li>
        <li x-text="number"></li>
        <li x-text="pincode"></li>
    </ul>
</div>
saim ansari
saim ansari

I'm Saim Ansari, a full-stack developer with 4+ years of hands-on experience who thrives on building web applications that leave a lasting impression. When it comes to tech, I'm particularly adept at Laravel, React, Tailwind CSS, and the Tall Stack