What Is Alpine.js and How Do You Use It?

The world of web development is chaotic—frameworks pop in and out of existence and things can be overwhelming for both new and experienced developers alike.

Unlike most web development frameworks, Alpine.js aims to be as simple as possible, yet powerful enough to deal with concepts like reactivity and side effects.

4

Getting Started With Alpine.js

Installing Alpine.js is quite simple. You only need to include the followingscripttag in your HTML:

Alternatively, you’re able to install Alpine.js in your project using Node Package Manager:

laptop with windows privacy settings and power on and off button icons.

Reactivity in Alpine.js

Create anindex.htmfile and add the following boilerplate code:

Thedeferattribute in thescripttag tells the browser to run the script only after it’s finished parsing the document.

Meta AI being used on a laptop and cellphone

Alpine.js provides several directives likex-datawhich it uses to store data andx-textwhich it uses to setinnerTextof the attached component. To use these directives, add the following code to your HTML.

The x-data directive stores an object with the keysnameandorganisation. you may then pass those keys into the x-text directive. When you run the code, Alpine.js will populate the values:

chatgpt pin code advice request.

How Alpine.js Compares With React

Alpine.js is a lightweight framework which makes it suitable for developing small projects and prototypes.

In larger frameworks like React, you usehooks likeuseEffect()to handle side effects in the component lifecycle. This hook runs a callback function whenever one of the elements of the dependency array changes:

Alpine.js logo with a person working on their computer in the background

To handle side effects in Alpine.js, you may use thex-effectdirective. For example, let’s say you want to watch a variable and log the value whenever it changes:

The first thing you might notice is that you do not need to specify a dependency. Alpine will simply listen for changes in all the variables passed tox-effect. The@clickdirective increments the number variable by 1.

Conditional Rendering in Alpine.js

Rendering elements conditionallyis something you’re able to do in frameworks like React. Alpine.js also allows you to conditionally render elements. It provides anx-ifdirective and a specialtemplateelement that you can use to conditionally render elements.

Create anotherindex.htmfile and add the same boilerplate code as before. Add the following code to the body of the HTML.

Thex-ifdirective is passed to thetemplateelement. This is important because it allows Alpine.js to keep track of an element that is being added or removed from the page. Thetemplateelement should contain one root-level element; the following code would violate that rule:

Building a To-Do Application With Alpine.js

It’s time to combine everything that you have learned so far and build a simple to-do application with local storage support. First, create a folder and populate it with anindex.htmfile and astyle.cssfile. Add the boilerplate code into the index.htm file and include a reference to thestyle.cssfile:

Do not worry about the CSS here, just copy thestyle.cssfile from thisproject’s GitHub repository.

To persist data after page reload, you need the Alpine.jspersistplugin. Add the CDN build of this plugin as ascripttag, just above the core Alpine.js CDN build:

In thebodydefine adivelement with anx-datadirective. This directive should hold an array calledallTasks. Then, add anh1element with the text “To-Do Application”.

The$persistplugin is a wrapper for theJavaScript localStorageAPI. It tells the browser to store the array in local storage, so that data remains intact even after page reload. Add aformwith asubmitdirective that also prevents the default submit action.

The$refsclause allows access to the DOM element with the “task"x-refdirective. The code also handles some validation and ensures that it does not add empty strings or duplicate tasks to the list. Before ending the form, add aninputelement with anx-refof “task” and a placeholder. Then add a button and set its type to “submit”.

Next, define a div with the class “items”. This div should contain two other divs: one with thex-dataset to an “uncompleted” array and the other set to a “completed” array. Both divs should have anx-effectdirective and the array should be wrapped in the$persistclause as shown earlier.

In the first div, add anh3tag with the text “Uncompleted”. Then for each element in theuncompletedarray, render adivthat holds the “controls” and the task itself.

The controls allow the user to delete an item or mark it as completed:

it’s possible to use thex-fordirective to iterate through an array and render elements. It is similar tov-forin Vue and theArray.map()array methodin React. The “controls” div contains two divs with the string “[M]” and “[R]”. These strings stand for “Mark as done” and “Remove”. You can replace these with proper icons if you wish.

Thex-showdirective sets an elementdisplayCSS property tononeif the value pointing to the directive is falsy. The second div in the “items” div is similar to the first one with a few notable exceptions: Theh3text is set to “Completed”, the “control” div’s first child has the text “[U]” instead of “[M]” and in this div’s@clickdirective,element.doneis set tofalse.

And that’s it, you’ve gone over the basics of Alpine.js and used what you learned to create a basic to-do application.

Making Alpine.js Code Easier To Write

When you start writing Alpine.js code, it can be difficult to wrap your head around. Luckily, code editors like Visual Studio Code provide a wide array of extensions that make development easier.

In the Extensions Marketplace, you can get the Alpine.js IntelliSense extension which makes it easier to work with directives. This can help improve your productivity when using Alpine.js in your projects.

Want more from Visual Studio Code? Need improved tools and productivity options? Try these Visual Studio Code extensions.

These films will leave you questioning humanity, but also wanting more.

Your phone is a better editor than you give it credit for.

Every squeak is your PC’s way of crying for help.

Don’t let someone else take over your phone number.

I found my TV was always listening—so I shut it down.

Technology Explained

PC & Mobile