Alpine.js is a new and lightweight JavaScript framework that offers easy-to-use directives to add behavior and functionality to web pages right from the markup.
In this shot, we will go over how to create a search component in Alpine.js.
Copy the starter template on the Bootstrap official website and add the CDN link to Alpine.js.
Add a search input field and list items so your page has the following content:
<!doctype html><html lang="en"><head><!-- Required meta tags --><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"><script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script><title>Hello, world!</title></head><body><div class="container my-5 py-5 px-5 mx-5"><!-- Search input --><input type="search" class="form-control" placeholder="Enter Keyword here"><!-- List items --><ul class="list-group mt-3"><li class="list-group-item">Apple</li><li class="list-group-item">Banana</li><li class="list-group-item">Guava</li><li class="list-group-item">Ape</li><li class="list-group-item">Bands</li></ul></div><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script></body></html>
The result of the code above should be as follows:
Use Alpine’s x-data
directive to store the list of search items.
Update the container div
to match the code below:
<div x-data="{ items: ['Apple', 'Banana', 'Guava', 'Ape', 'Bands'] }">
<!-- Search input -->
<input type="search" placeholder="Enter Keyword here">
<!-- List items -->
<ul>
<template x-for="item in items">
<li x-text="item"></li>
</template>
</ul>
</div>
<div
x-data="{
search: ''
items: ['Apple', 'Banana', 'Guava', 'Ape', 'Bands']
}">
<!-- Search input -->
<input type="search" placeholder="Enter Keyword here" x-model="search">
<!-- Other code -->
</div>
x-data
object:get searchResults () {
return this.items.filter(
i => i.startsWith(this.search)
)
}
This function checks for items in your list that start with the user input.
Update x-for
to display results from the search rather than the initial list.
<template x-for="item in searchResults"></template>
Now, the search bar works when users type in it.