Alpine.js x-text Directive — Complete Guide with Examples
In this tutorial, you'll learn about the Alpine.js x-text directive. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Alpine.js x-text directive sets an element's text content to the result of a JavaScript expression, automatically escaping HTML for safe rendering of user data.
What You'll Learn
By the end of this tutorial, you'll use x-text to display reactive data, combine multiple values with template literals, understand HTML escaping, and know when to use x-text vs x-html.
Why It Matters
Displaying dynamic data is the most basic requirement of any interactive UI. x-text gives you a safe, simple way to output state values without worrying about XSS Attacks or manual DOM updates.
Real-World Use
Durga Antivirus Pro's scan dashboard uses x-text to display real-time statistics: files scanned, threats detected, and scan duration. The values update as the scan progresses, and the HTML escaping ensures that file names with special characters display safely.
Where This Fits in Your Learning Path
flowchart LR
A["x-data Directive"] --> B["x-bind Directive"]
B --> C["**x-text Directive**"]
C --> D["x-html Directive"]
D --> E["Advanced Alpine Patterns"]
style C fill:#f97316,stroke:#c2410c,color:#fff
style A fill:#e5e7eb,stroke:#9ca3af,color:#374151
style E fill:#22c55e,stroke:#16a34a,color:#fff
What is x-text?
x-text sets the innerText of an element to the string value of a JavaScript expression. Any HTML tags in the expression are escaped and displayed as literal text.
Think of x-text like a label maker. You feed it text, and it prints exactly what you give it. If you feed it "bold", it prints the characters <b>bold</b> rather than making the text bold.
<div x-data="{ greeting: 'Hello World' }">
<h1 x-text="greeting"></h1>
</div>
Expected output: "Hello World" displayed as plain text in the h1 element.
Displaying Multiple Values
Combine multiple state properties using template literals or string concatenation.
<div x-data="{ firstName: 'Alice', lastName: 'Smith', age: 30 }">
<p x-text="`${firstName} ${lastName} is ${age} years old`"></p>
</div>
Expected output: "Alice Smith is 30 years old".
Safe HTML Escaping
x-text escapes HTML tags, preventing cross-site scripting attacks. This is critical when displaying user-generated content.
<div x-data="{ userInput: '<script>alert(\"xss\")</script>' }">
<p x-text="userInput"></p>
</div>
Expected output: The literal text "" is displayed. The script is NOT executed because x-text escapes it.
Using Expressions in x-text
Any valid JavaScript expression works: ternary operators, function calls, arithmetic, and property access.
<div x-data="{ price: 29.99, tax: 0.08, quantity: 2 }">
<p x-text="`Total: $${(price * quantity * (1 + tax)).toFixed(2)}`"></p>
</div>
Expected output: "Total: $64.78" (29.99 * 2 * 1.08).
Conditionally Displaying Text
Use ternary operators to show different text based on state.
<div x-data="{ isLoggedIn: false, username: '' }">
<p x-text="isLoggedIn ? `Welcome back, ${username}` : 'Please log in'"></p>
<button @click="isLoggedIn = !isLoggedIn; username = 'Alice'" x-text="isLoggedIn ? 'Logout' : 'Login'"></button>
</div>
Expected output: Shows "Please log in" initially. After clicking Login, shows "Welcome back, Alice".
Common Mistakes
1. Using x-text for HTML content
If you need to render HTML tags, use x-html instead of x-text. x-text escapes all HTML.
2. Forgetting template literal syntax
Using single quotes instead of backticks breaks string interpolation. Always use backticks for ${} expressions.
3. Using x-text on void elements
x-text doesn't work on <img>, <input>, <br>, or other void elements. Use x-bind:alt or x-bind:value instead.
4. Overusing x-text when the content is static
If the content never changes, just write it directly in the HTML. x-text is only needed for dynamic data.
5. Trying to display objects with x-text
x-text on an object displays "[object Object]". Use JSON.stringify or access specific properties.
Practice Questions
What does x-text do? It sets the element's innerText to the string value of a JavaScript expression.
Does x-text escape HTML? Yes. HTML tags are escaped and displayed as literal text, preventing XSS attacks.
How do you display multiple variables in one x-text? Use template literals: x-text="
Hello ${name}, you are ${age}".What's the difference between x-text and innerHTML? x-text uses innerText (HTML is escaped). innerHTML renders HTML tags.
Can x-text use ternary operators? Yes. Any JavaScript expression works, including ternaries: x-text="condition ? 'Yes' : 'No'".
Challenge
Build a live markdown preview counter. Use x-text to show character count, word count, and reading time estimate as the user types in a textarea.
FAQ
Mini Project
Build a real-time character counter for a tweet composer. Show the character count, remaining characters, and a warning when approaching the limit.
<div x-data="{ tweet: '' }">
<textarea x-model="tweet" maxlength="280" placeholder="What's happening?" class="w-full p-2 border rounded"></textarea>
<div class="flex justify-between mt-2">
<span x-text="`${tweet.length} characters`"></span>
<span x-text="`${280 - tweet.length} remaining`" :class="tweet.length > 240 ? 'text-red-500 font-bold' : 'text-gray-500'"></span>
</div>
<p x-text="tweet.length > 260 ? 'You are close to the limit!' : ''" class="text-red-500 mt-1"></p>
</div>
What's Next
Continue with content display directives:
| Tutorial | What You'll Learn |
|---|---|
| x-html Directive | Render HTML content dynamically |
| x-ref Directive | Access DOM elements directly |
Related topics: JavaScript template literals, XSS prevention.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro