Let’s create a tag input!
Tag inputs are a great way to add tags to a list. They are used in many different applications, such as social media, to allow users to add new tags to a post.
Advantages of tag inputs:
The structure of the tag input
x-data
attribute is used to define the data of the componentx-for
attribute is used to loop through the tags
array:key
attribute is used to uniquely identify each item in the loopx-text
attribute is used to display the value of the tag
variable@click
attribute is used to add a new tag to the tags
array when the user clicks the close buttonNote: The classes are remove for clarity.
<div
x-data="{
tags: [],
addTag(tag) {
if (tag.trim() !== '') {
this.tags.push(tag.trim());
}
},
removeTag(index) {
this.tags.splice(index, 1);
}
}">
<!-- Tag Input -->
<div
class="w-full"
x-data="{ newTag: '', tags: [] }">
<!-- Input Field -->
<input
x-model="newTag"
@keydown.enter.prevent="
if (newTag.trim() !== '') {
tags.push(newTag.trim());
newTag = '';
}
"
type="text"
placeholder="..."
/>
<!-- Tags will be added here -->
<div>
<template
x-for="(tag, index) in tags"
:key="index">
<div
>
<span x-text="tag"></span>
<button
@click="tags.splice(index, 1)"
class="ml-2">
<!--- Close Icon goes here -->
</button>
</div>
</template>
</div>
</div>
</div>
Hope you enjoyed this tutorial.
"I bought a beautiful theme from Lexington a couple weeks ago. I didn't know Astro at the time, but Michael helped me get set up and really went above and beyond with his support. Now I'm happily redoing my site to look gorgeous with his template."
Stuart
Creator of saasydb.com
"Michael is one of the best designers on Twitter, would highly recommend his Lexington Themes if you want something in tailwind that doesn’t look the same as everyone else!"
Alex Hughes
letsloopin.com
Get lifetime access to every theme available today for $199 and own
them forever. Plus, new themes, lifetime updates, use on unlimited
projects and enjoy lifetime support.
No subscription required!
Lexington
Beautifully designed HTML, Astro.js and Tailwind themes! Save months of time and build your startup landing page in minutes.