Laravel

1st of August 2023

Alpine JS: The final piece of reactivity for the TALL Stack

Discover Alpine.js, a lightweight JavaScript framework that complements the TALL stack, offering simplicity and efficiency in frontend development. Learn how Alpine.js integrates seamlessly with Tailwind CSS, Laravel, and Livewire, providing a powerful solution for modern web applications.


The dynamic landscape of web development is continually evolving, witnessing the emergence of diverse frameworks and libraries to cater to the needs of modern web applications. Among these contenders, Alpine JS has carved a prominent niche for itself as a lightweight and user-friendly JavaScript framework. While Alpine JS holds its ground as an excellent choice for most websites, its true potential shines through when paired with Livewire. This powerful coupling is reinforced by the fact that both Alpine JS and Livewire were created by Caleb Porzio, establishing a strong synergy between the two technologies.

The TALL stack, an acronym for Tailwind CSS, Alpine JS, Laravel, and Livewire, has been gaining traction as a modern alternative to the traditional LAMP and MEAN stacks, we have written about it here. Each component in the TALL stack brings a unique set of features and benefits, with Alpine JS standing out as an essential frontend tool that complements Livewire, a powerful PHP-based backend framework. Let's delve into what Alpine JS is and how it fits seamlessly into the TALL stack.

What is Alpine JS?

Alpine JS is a JavaScript framework designed for developers who prefer a minimalistic approach to frontend development. Unlike heavier alternatives like React or Vue.js, Alpine JS weighs in at a mere 7kb (minified and gzipped). It focuses on providing declarative syntax and the ability to enhance existing HTML, rather than completely replacing it.

At its core, Alpine JS is based on a few fundamental principles:

  1. Declarative Syntax: Alpine JS leverages HTML attributes to control behaviour, making it easy for developers to understand and work with the codebase.
  2. Minimal Learning Curve: As Alpine JS primarily works with standard HTML and a few custom attributes, developers familiar with HTML and JavaScript can quickly get up to speed with the framework.
  3. No Build Step Required: Alpine JS doesn't require complex build processes, making it an attractive option for projects that don't need the additional overhead of a build toolchain.
  4. Framework Agnostic: Alpine JS is independent of any specific backend or frontend framework, allowing it to be easily integrated into existing projects.

Alpine.js in the TALL Stack

When combined with Tailwind CSS, Laravel, and Livewire, Alpine JS completes the TALL stack, offering an end-to-end solution for building modern web applications. Here's how Alpine JS fits seamlessly within the TALL stack:

  1. Complementing Tailwind CSS: Tailwind CSS provides a utility-first approach to styling, giving developers a vast array of pre-defined classes to quickly style elements. Alpine JS takes advantage of this by using these classes to control element behaviour and interactivity without the need for additional JavaScript.
  2. User Interactivity with Alpine JS: Alpine JS shines when it comes to creating interactive elements in your web application. It enables developers to easily add features like dropdowns, modals, toggle buttons, and more, all within the HTML markup using the Alpine JS directives.
  3. Enhancing Livewire Components: Livewire, a Laravel package for building reactive interfaces, benefits from Alpine JS' capabilities. While Livewire handles backend interactivity, Alpine JS can handle the frontend interactivity, allowing developers to leverage the best of both worlds without compromising simplicity.
  4. Efficient and Fast: With Alpine JS being lightweight, it ensures that your web application remains performant, loading quickly and providing a smooth user experience.

Getting Started with Alpine JS

To begin using Alpine JS in your TALL stack project, follow these simple steps:

  1. Include Alpine JS: Start by including Alpine JS in your project. You can either download it directly from the official website or use a package manager like npm or yarn to install it.
  2. Add Alpine JS Directives: Utilise Alpine JS directives to add interactivity to your HTML elements. For example, use x-data to define your data, x-show to toggle element visibility, and x-on to bind events.
  3. Combine with Livewire Components: Use Alpine JS alongside Livewire components to handle the frontend and backend logic efficiently, resulting in a more organised and maintainable codebase.

A simple Livewire component with Alpine JS

As noted above, here at Camino Dev like to use Alpine JS as a final sprinkle of javascript to compliment Livewire. This provide a slicker user experience, using Javascript when we want instantaneous interactions and using Livewire for more heavy lifting.

Here is a super simple Livewire Component that mainly uses Alpine Js

Use the livewire artisan command

php artisan make:livewire navbar-dropdown

This will create two files

The blade file navbar-dropdown.blade.php. And the Livewire component NavbarDropdown.php

Below is a slightly simplified version of the component we use for main clients at Camino Dev. This code will work except for the toggle. Feel free to email us to get the final component that we use at Camino Dev.

In navbar-dropdown.blade.php use the following code.

<div>
    <div x-data="{ open: false }" @keydown.escape.stop="open = false; focusButton()" @click.away="open = false;"
        class="ml-3 relative">
        <div class="border-transparent border-b-2 hover:border-primary-500 pb-0.5">
            <button type="button" class="max-w-xs  flex items-center text-sm rounded-full  " id="user-menu-button" x-ref="button"
                @click="open = !open">
                <span class="sr-only">Open user menu</span>
                {!! $avatar !!}
            </button>
        </div>
        <div x-show="open"
            class="origin-top-right absolute right-0 mt-2 w-48  rounded-md shadow-lg bg-white dark:bg-gray-700 ring-1 ring-black ring-opacity-5 focus:outline-none"
            role="menu" aria-orientation="vertical" aria-labelledby="user-menu-button" style="display: none;">


            <a wire:navigate.hover href="/profile"
                class="cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800 block px-4 py-2 text-sm">{{ __('Profile') }}
            </a>


            <span class="flex justify-between hover:bg-gray-100 dark:hover:bg-gray-800  px-4 py-2 text-sm">{{ __('Dark_Mode') }}
                <x-input.toggle-small wire:click="save('darkMode')" id="navDarkMode" :checked="$user->setting('darkMode')" />
            </span>


            <a href="/logout" class="hover:bg-gray-100 dark:hover:bg-gray-800 block px-4 py-2 text-sm">{{ __('Sign Out') }}</a>
        </div>
    </div>
</div>


In the NavbarDropdown.php use the following code

<?php

namespace App\Livewire;

use Auth;
use Livewire\Component;

class NavbarDropdown extends Component
{
    public $user;

    public $avatar;

    public $page;

    protected $listeners = ['updateAvatar' => 'updateAvatar'];

    public function mount()
    {
        $this->user = Auth::user();
        $this->avatar = $this->user->avatarHtml();
    }

    public function updatedPage()
    {
        $this->dispatch('reloadAppPage', $this->page);
    }

    //Really just for dark mode
    public function save($settingName, $isBoolean = 1, $settingValue = '')
    {
        if ($settingName) {
            if ($isBoolean) {
                $settingValue = ! $this->user->setting($settingName);
            }

            $setting = [$settingName => $settingValue];
            $this->user->settings($setting);
            if ($settingName == 'darkMode') {
                $this->dispatch('darkModeToggle', $settingValue);
            }
        }
    }

    public function updateAvatar()
    {
        $this->avatar = Auth::user()->avatarHtml();
    }

    public function render()
    {
        return view('livewire.navbar-dropdown');
    }
}


You can see that the above blade file has no interactivity from Livewire. We hand that off to Alpine Js. Keeping things extremely simple.

Conclusion

Alpine JS is undoubtedly a game-changer for developers seeking simplicity and efficiency in frontend development. Its lightweight nature, declarative syntax, and seamless integration within the TALL stack make it a compelling choice for modern web applications. By leveraging Alpine JS alongside Tailwind CSS, Laravel, and Livewire, developers can create powerful and interactive interfaces without the complexity of heavy JavaScript frameworks. So, if you're looking to streamline your frontend development in the TALL stack, give Alpine JS a try, and experience the power of simplicity firsthand.

Read more of insights about the world of technology

  • All Posts

31st of January 2024

Pair programming with AI - How AI has changed my work life

Explore the transformative impact of GitHub Co-Pilot and ChatGPT on software development. Learn how integrating AI tools like Cursor into the coding workflow can mimic pair programming, enhancing productivity and creativity in the digital realm.

Read Post
Image of Vinoflow app on laptop and mobile

17th of January 2024

Revolutionising Wine Subscriptions: How Camino Dev and Vinoflow are changing the game with the TALL Stack and Livewire 3

Vinoflow is a testament to the capabilities of the TALL stack in creating dynamic, user-friendly, and efficient web applications. Its focus on the wine subscription market showcases how targeted solutions can be developed using this technology stack, offering both technical robustness and business agility. This platform is not just a technological advancement, we believe it's a game changer for the wine subscription industry.

Read Post
Tall stack logos

31st of July 2023

The Power of the TALL Stack: Building Modern Web Applications

Discover the power and flexibility of the TALL Stack, a combination of Tailwind CSS, Alpine.js, Laravel, and Livewire. Learn how this innovative stack is revolutionising web development, offering scalability, ease of use, and efficiency. Explore the benefits of Single Page Applications (SPAs) with SEO-friendly server-side rendering. Join us at Camino Dev to find out how we can tailor these technologies to your unique needs.

Read Post
Abstract image representing data

20th of February 2023

Utilising Data Analytics in Small Business Decision Making

Discover how data analytics can be a game-changer for small businesses. From understanding customer behaviour to improving operational efficiency, learn how Camino Dev's custom software solutions can empower your decision-making.

Read Post
Contrived code example of upgrading to Laravel

25th of January 2023

Upgrading Your Laravel Project: Best Practices and Common Pitfalls

Discover the best practices and common pitfalls for upgrading your Laravel project in this short guide.

Read Post
Image of people around a whiteboard

30th of November 2022

Embracing Digital Transformation: A Roadmap for Small and Medium-Sized Businesses

Explore the journey of digital transformation for small and medium-sized businesses (SMBs) with Camino Dev. From assessing current infrastructure to building custom solutions aligned with your unique goals, our roadmap helps guide SMBs towards enhanced operations, growth, and innovation. Learn how tailored technology can empower your business in the digital age.

Read Post

Have any questions?

Feel free to get in touch to set up a meeting or to ask us any questions you may have.