Snowy mountain

Tailwind for interactions - Alpine.JS

07 December 2020

As you can probably see from my earlier post about Lit-HTML and Haunted, I've been looking at alternatives to React for adding interactivity to pages without a whole lot of technical debt and without shipping a gigantic package size to the client.

One of the great ways of getting this done is with Alpine.JS. A framework by Caleb Porzio - a developer from the Laravel community. Alpine JS is pretty different from some of the other Javascript libraries/frameworks out there in a few ways I'll get into:

Firstly, Apline is designed from the ground up to work in a traditional server side rendered (SSR) app - eg an application using frameworks like Rails, Laravel or .net. You can have a web app just pushing HTML to a browser and you don't need to scorch it all to the ground before adopting Alpine. All you need to do is pull it in from a CDN and get started - just like the old Jquery days. No build step.

If you've used React before, you'd be used to pulling HTML into your Javascript and using babel to convert it back into React components. This is handy, as the logic is colocated with the markup and you can see exactly what part of the markup is being interracted with.

Alpine goes the opposite way. Instead of pulling HTML into your JavaScript, you can instead manage all your interactivity inside your HTML - and you don't even need to worry about creating a new JS file. This is especially good in server side rendered applications - which are literally designed for producing HTML based on data.

In my experiments with Alpine, I've also found that it's pretty close to being able to do an almost redux - style state management. You can have your child elements create events which are listened to by the parent, which can in turn run these events and their payload through a reducer function to update the state - which will then filter this data down to the child elements.

Also, the child elements of your Alpine component can react to the component state in a number of handy ways. You can bind their text or innerHTML to values held in the state. You can decide whether they get shown or not based on a vlues truthiness. You can render out a number of elements based on an array/list by using the template tag. And you can use "x-spread" to reuse logic.

Alpine also has built in transitions for when elements get added and removed from the page which is pretty tasty.

So far in my gardening app, I've been using Alpine.JS for a few different things: form validation (with Iodine helping out), modals (for deleting and changing some items), and some transitions.

I'd definitely recommend giving it a try.

Back to blog