Using x-for in Alpine JS [Complete Guide]

Alpine JS offers x-for loop to iterate over an array of data. You can also use x-for loop to print simple iterations on a specified range.

Simple For Loop with x-for in Alpine JS

You can iterate over a simple specified range using x-for. This will iterate only on the specified range. Here is an example below to use x-for on a specified range.

This will print 10 numbers on the web page. Now, let’s see how to iterate over real data that you will get from an API.

Using x-for on Array of Objects API Data

When you are working with APIs, you probably have data as an array of objects. The example below uses an array of users and prints the name of each user.

How to Access the index in x-for loop

You can access the index inside x-for loop with a slight change in syntax. The following example illustrates how to use an index.

The above example will display names with indexes.

Specifying Key in x-for loop in Alpine JS

When working with modern frameworks, specifying a key while iterating is required. You can add a key with :key attribute inside x-for loop. It is not recomended to use index as a key because it may cause issues in the web page as multiple items will get same key. The following example explains how to specify a key in x-for iterations.

Using x-if Inside x-for in Alpine JS

You can use x-if inside x-for with another template. The following example ilustrates how to use x-if in alpine JS. You can also specify multiple if conditions inside x-for.



Alpine JS offers x-for loop to iterate over an array which helps to display a template in the web page. By using x-for loop, you can get rid of copy pasting the same code again and again. You can read more about x-for on official documentation of alpine JS.

Latest articles

Related articles