Searching within lists with Alpine.js

a quick script for matching patterns in arrays

// updated 2025-09-19 09:39

For an Alpine.js app, if we have a list (i.e. a JavaScript array) of items, then we can search through the list by making use of properties within the x-data directive object:

1<div
2  x-data="{
3    search: '',
4
5    items: ['aa', 'bb', 'ba', 'ab'],
6
7    get filteredItems() {
8      return this.items.filter(
9        item => item.includes(this.search)
10      )
11    }
12  }"
13>
14    ...
15</div>

So breaking down the above x-data directive:

  • search provides a state variable for the current search query
  • items provides a state variable for the list (an array of strings)
  • get filteredItems() provides a method to return the results of a search on a list
    • we use the keyword this to refer to the entire object within x-data
      • note how we use this whenever we want to reach any other property or method in this object
    • we then filter on the array with this.items.filter(...)
      • this higher-order filter method finally looks at each item in the array
      • ...and returns any item that contains (includes) the same characters as in the search query

Demo

We can try it in this demo (try it with CAPS LOCK on or with initial spaces!):

First notice that we use the following just for user experience:

  • toLowerCase() to avoid case-sensitivity
  • trim() to remove whitespace

Also note the following:

  • we use x-model with the <input> tag to bind the search property of x-data
  • we use an unordered list
    • inside the list we use a <template> tag that represents each item in this dynamic list
      • item refers to each item (a string element) in the filtered array (filteredItems) that changes with each search
      • the :key attribute should provide a unique identifier for debugging purposes
    • each item then displays a list item using an x-text directive
      • the value of x-text then displays the item
⬅️ older (in textbook-alpinejs)
🏔️ Hiding and showing content with Alpine.js
newer (in textbook-alpinejs) ➡️
Templating and styling with Alpine.js 🏔️
⬅️ older (in code)
🏔️ Hiding and showing content with Alpine.js
newer (in code) ➡️
Templating and styling with Alpine.js 🏔️
⬅️ older (posts)
🏔️ Hiding and showing content with Alpine.js
newer (posts) ➡️
Templating and styling with Alpine.js 🏔️