Description: The x-text directive in AlpineJS allows you to display reactive data from your x-data scope as the text content of an HTML element. This content updates automatically whenever the underlying data changes. For Python developers familiar with frameworks like Django or Flask, this is conceptually similar to using template variables (e.g., {{ my_variable }}), but x-text operates entirely on the client-side, enabling dynamic updates without page reloads.
The x-text directive is fundamental for displaying reactive data. It directly manipulates the textContent property of the HTML element it's applied to.
x-text="propertyName": This is the most common usage. AlpineJS will look for a data property named propertyName within its current x-data scope. The text content of the HTML element will be set to the value of this property. If propertyName's value changes, the displayed text will reactively update.
<div x-data="{ message: 'Hello from Alpine!' }">
<p>The message is: <span x-text="message"></span></p>
<!-- Output: The message is: Hello from Alpine! -->
</div>
x-text="'Hello, ' + name" (JavaScript expressions): You're not limited to just displaying a single property. x-text can evaluate any valid JavaScript expression. This allows for string concatenation, calling JavaScript functions, or performing simple logic directly within the template. The result of the JavaScript expression will be set as the element's text content.
<div x-data="{ user: { firstName: 'Alex', score: 100 } }">
<p x-text="'User: ' + user.firstName + ' has a score of ' + user.score"></p>
<!-- Output: User: Alex has a score of 100 -->
<p x-text="`Welcome, ${user.firstName.toUpperCase()}!`"></p>
<!-- Output: Welcome, ALEX! (using template literals) -->
</div>
In these examples, string literals like 'User: ' are combined with reactive data properties (user.firstName, user.score) using JavaScript's string concatenation (+) or template literals (`${...}`).
Trying to render HTML with x-text:
A frequent misunderstanding is attempting to use x-text to render HTML content. If you have a data property like myHtml = "<strong>Important</strong> note", applying x-text="myHtml" will display the literal string "<strong>Important</strong> note" on the page, not "Important note". This is because x-text sets the textContent of an element, which treats all input as plain text, effectively escaping any HTML tags. This is a security feature to prevent accidental XSS vulnerabilities.
If you explicitly need to render HTML from a string (and you fully trust the source of that HTML), you should use the x-html directive instead: <div x-html="myHtml"></div>. Be very careful with x-html and ensure the HTML content is sanitized if it comes from user input.
Forgetting quotes for literal strings in expressions:
When combining static text with reactive data properties in a JavaScript expression, it's crucial to remember that JavaScript string literals must be enclosed in quotes (single ', double ", or backticks ` for template literals).
For example, x-text="'Status: ' + currentStatus" is correct. If you omit the quotes around 'Status: ', like x-text="Status: + currentStatus", JavaScript will interpret Status as a variable, not a string, leading to errors (often a SyntaxError or ReferenceError). Python developers used to f-strings (e.g., f"Status: {current_status}") might overlook this, as Python's f-string syntax handles the literal part differently.
Assuming x-text automatically formats data:
The x-text directive displays data "as is". It does not perform any automatic formatting for dates, numbers, currency, or other data types. If you have a JavaScript Date object, x-text will display its default string representation (which can be quite verbose). Similarly, a number like 12345.6789 will be displayed as such.
To format data:
x-data methods or computed properties: This is often the cleanest approach. You can define a method or a "getter" in your Alpine component that returns the already formatted string.x-text expression: You can call JavaScript's built-in formatting functions (e.g., myDate.toLocaleDateString(), myNumber.toFixed(2), myNumber.toLocaleString()) or custom utility functions directly inside the x-text attribute. For example: x-text="new Date(eventDate).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })" or x-text="'Price: $' + productPrice.toFixed(2)".Current System Status:
Character count: 0
x-text vs. x-html (Gotcha Demo)Our data property htmlString contains:
Using x-text="htmlString":
Notice how HTML tags (<em>, <strong>) are displayed as literal text, not rendered.
Using x-html="htmlString" (for comparison):
Here, HTML tags are rendered. Use x-html with caution and only with trusted content to avoid XSS.
Raw timestamp:
Raw number:
Displaying with x-text and JavaScript formatting:
Formatted Date (US locale):
Formatted Date (UK locale, long):
Formatted Number (currency, USD):
Formatted Number (2 decimal C):
Remember: x-text itself doesn't format. You must use JavaScript expressions or pre-format data in your component's logic.