How to Use x-text in AlpineJS

In this section, we will explore how to utilize x-text in Alpine.js. x-text is a straightforward directive used for displaying text data dynamically.

Example 1

Simply display text messages using x-text.

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

Example 2

Alpinejs x-text with click event.

<div x-data="{ count: 0 }">
    <button @click="count++">Increment</button>

    <span x-text="count"></span>
    <button @click="count--">Decrement</button>
</div>

Example 3

Alpinejs x-text with object.

<div x-data="employee">
    <p x-text="name"></p>
    <p x-text="email"></p>
    <p x-text="age"></p>
</div>

<script>
    document.addEventListener("alpine:init", () => {
        Alpine.data("employee", () => ({
            name: "John Doe",
            email: "[email protected]",
            age: "25",
        }));
    });
</script>

Alpinejs 3 x-text with array & x-for loop.

<ul x-data="employee">
  <template x-for="person in people" :key="person.id">
    <li x-text="person.name"></li>
  </template>
</ul>
<script>
  document.addEventListener('alpine:init', () => {
    Alpine.data('employee', () => ({
      people: [
        { id: 1, name: 'Jhon' },
        { id: 2, name: 'nike' },
        { id: 3, name: 'sam' },
      ],
    }));
  });
</script>

Example 4

Alpinejs x-text with show and hide message with ternary operator.

<div x-data="{ show: false}">
    <p x-text="show == true ? 'message is visible' : 'message is hide'"></p>
    <button @click="show=true">show message</button>
</div>

Much better

<div x-data="{ show: false}">
  <p x-text="show == true ? 'message is visible' : 'message is hide'"></p>
  <button @click="show=!show">show message</button>
</div>

Example 5

You can also utilize x-text within a button with a working click event.

<div x-data="{ show: false}">
    <p x-text="show == true ? 'message is visible' : 'message is hide'"></p>
    <button @click="show=!show" x-text="show == true ? 'hide message' : 'show message'"></button>
</div>
x-text  with button
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