x-for Directive
Loop over arrays or objects – like v-for in Vue.
What is x-for?
x-for loops over an iterable (array or object) and creates DOM elements for each item. It must be placed on a <template> tag and requires a unique :key for each iteration to help Alpine track item identity.
When to Use
Use x-for whenever you need to render a list of items dynamically. It’s similar to v-for in Vue or map() in React.
Array Example
Code
<div x-data="{ items: ['apple', 'banana', 'cherry'] }">
<template x-for="(item, index) in items" :key="index">
<p x-text="item"></p>
</template>
</div>Object Example
Code
<div x-data="{ person: { name: 'John', age: 30 } }">
<template x-for="(value, key) in person" :key="key">
<p x-text="key + ': ' + value"></p>
</template>
</div>Importance of :key
Always provide a unique :key (e.g., item id). Without it, Alpine may reuse DOM elements incorrectly, causing weird behavior when the list order changes. Use a stable identifier, not the array index, for reliable performance.
💡 Tip
If your items are objects with unique IDs, use :key="item.id" instead of the index. This helps Alpine reuse DOM elements efficiently.
Helpful? Share this page!↑ Back to top