Alpine.js beginner tutorial: create a todo app with minimal lines of code.

Ever dreamt of a minimalistic js framework, that’s not heavy, easy to set up, and could solve the majority of problems with minimal lines of coding. Introducing Alpine.js.

Alpine.js is a minimal framework that is reactive and declarative( i.e, you can manipulate dom objects directly without js ). The syntax is inspired by frameworks like Angular, Vue and no compilation required for deploying. You might not know Angular or Vue, but you can learn this framework within a day. That’s how easy and minimal it is.

Where can you use this framework?

Well, Alpine.js might not be useful for developing a full-fledged SPA like Angular or React, you can still use it for developing small and even some medium size projects. If you want to develop an MVP or Proof of concept just for showing a demo to clients, I highly recommend this to you.

Alpine vs Jquery ( Not a Jquery hater ):

If you have worked on jquery projects, you might have guessed that AlpineJS goes head to head with Jquery. AlpineJS has almost all the features that Jquery has but in a more efficient way ( which we will explore shortly ). Below are some feature comparisons.

  • AlpineJS is lightweight  ( 7.1kB gzipped  – 21.9kB minified ) compared to Jquery ( 32.5kB gzipped – 92.4kB minified ).
  • AlpineJS is reactive and declarative in nature, Jquery, on the other hand, everything ( accessing and manipulating DOM ) should be done through scripting.
  • Because you can manipulate DOM directly in AplineJS you can finish the project with minimal lines of code compared to Jquery.

Enough of promoting AlpineJS ( which i am not doing ), We will jump to coding.

Todo App:

This todo app will include the following functionality

  • Add an item to the list.
  • Remove an item from the list.
  • Check a particular item.
  • View the checked items separately.

We will have only one html file in our project and we will go through each and every line.

Header section:

In the header section, we include the alpine’s CDN. There are other means of installing the framework using npm, but for the sake of this tutorial, we will include their CDN.

CDN link: https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js ( for production you may want to use a specific version. refer to this link ).

Header section

We have a style with the class “strike” for representing an item that is checked.

Script section:

This section includes the whole js code for our todo list app.

Script section

  1. We have our dataObject which contains all the functions and properties of our app.
  2. newItemName property will contain the new name for the item to be added.
  3. Items is an array, which contains our to-do list.
  4. showChecked is a boolean property that shows/hides the checked list.
  5. addItem function as the name implies adds a new item to the list.
    • On the first line of the function, we are just checking that the newItem is not empty, we don’t want empty items in our list.
    • { id:<id number>, name: <our name>, checked: <true/false> } is the item format. We generate a random number for id because it will be easy to uniquely identify an element in the list.
    • Next, we empty the newItem property, to make the input empty and let the user enter a new item.
    • deletItem function deletes a particular item from the list using the unique id that we generated while creating.
    • checkItem function will check a particular item ( by toggling the checked property of an item ).

Note: Don’t use arrow notation for declaring functions as it does not have its own ‘this’ reference, so inside arrow function when you reference this.newItemName you are not referring to the one inside the object, rather the global declaration of the same. ( refer to this link: https://dmitripavlutin.com/differences-between-arrow-and-regular-functions/#1-this-value).

New Item input functionality:

Now we come to the html part.

to add new item to the list

One the first glance we see there are some unknown attributes in our code ( x-data, @click…etc ) they are not in-built with html, rather syntax for alpine js. We will explore one by one.

x-data:

x-data is the entry point of an alpine js project. Notice that we provide the dataObject to this attribute, this lets the framework know what are the properties and functions that we are using in our application.

x-model:

Next the input field is where we enter the new item’s name, here we notice x-model attribute ( if you know angularjs, you would have figured out what this means ), simply put this attribute binds the property newItemName to our input field, meaning whatever we type in will be updated in the binded variable, in our case its newItemName.

@click:

This attribute represents the usual onclick functionality on an HTML component. Here we call addItem() function to add a new item to the list with the name entered in the previous input field.

Note: This attribute has additional property, @click.away which triggers the function when we click outside that element.

Listing functionality:

Here we list all the items in the todo list.

Listing todo items

x-for:

x-for lets you repeat an HTML component. Here we loop items ( containing our todo list ), to display in a li tag. Note that we are using x-for in a template tag, this is because alpine is working on our real DOM and not a virtual dom like react nor does it have a complex change detection system like angular, so it is making use of template tag to render after the loop has finished executing ( refer link: https://www.w3schools.com/tags/tag_template.asp ). 

‘data in items’ means data will have each and every element of items when looping.

@change:

This is the same as onchange functionality on an HTML component. Here we have a checkbox that represents whether a particular item has been checked or not, this is done by calling checkItem(data.id) function which updates the checked property of our element based on the id passed to it.

:checked:

This is the same as the checked attribute in an input field. Here we pass data.checked ( checked property of a particular element in our todo list ) to check/uncheck this field.

x-text:

On the next line we see a span tag displaying the list item’s name, for this we use x-text attribute, what this does is it replaces the content of a particular tag to the given text value.

:class:

This is a very useful property, using this we can dynamically add and remove a class to an HTML component. :class=”{‘strike’:data.checked}” means if data.checked is true then strike class will be included in the tag’s class list.

Next, we have a button that calls deleteItem function, this deletes a particular item in the todo list based on the given id.

Displaying checked items:

In this section we display our checked items from our list.

Display checked items

On the first line we have a button doing two things, toggling showChecked property ( yes!, we can do this on line ) and change the button’s text ( hide checked / show checked ) based on the same.

x-show:

x-show attribute will show and hide a particular component based on the value given to it ( to hide, it places ‘display: none‘ on the element ). Here we have ‘.transition.in’ property along with it, this is one of many transition functionality that alpine offers. ( refer: https://github.com/alpinejs/alpine), when x-show triggers the content slides in.

Note: it is not a requirement to use transition everytime with x-show.

Next, we have the same listing function but filtering out only the checked once using items.filter(d=>d.checked).

That’s it. Check below screen show for the result.

Result:

result

Additional attributes:

These are some additional attributes that we did not use in our project.

x-init:

x-init is used with x-data at the starting of our application which is used to initialise property values, this is called right after x-data intialises.

example:

<div x-data="{ foo: 'bar' }" x-init="foo = 'baz'"></div>, this will result in baz.

x-if:

This is similar to x-show, but x-if will completely remove a particular element from the page.

example:

<template x-if="true"><div>Some Element</div></template>

Note: x-if should also be used in template tag, for explanation refer x-for above.

x-ref:

x-ref allows you to refer to a DOM element and obtain its object, so that we can use all the associated DOM properties.

example: <div x-ref="foo"></div><button x-on:click="$refs.foo.innerText = 'bar'"></button>, on clicking the button, the div’s content is changed to bar.

There are many other functions that alpine has but for the sake of simplicity, We are not covering those in detail in this tutorial. The above code is enough to get you started with alpine and build amazing applications.

Have fun developing!

Github: https://github.com/kishork2120/todoapp-alpine

2 thoughts on “Alpine.js beginner tutorial: create a todo app with minimal lines of code.

  1. I was suggested this web site by my cousin. I am not sure whether this post is written by him as no
    one else know such detailed about my trouble. You
    are wonderful! Thanks!

Leave a Reply

Your email address will not be published.

Pin It on Pinterest