Back

Getting started with Alpine.js

Getting started with Alpine.js

Using Alpine.js, web developers can create interactive and reactive user interfaces on the web. Alpine js is based on Vue.js, which makes it easier for vue developers to use, but it is designed to be lighter and more minimalistic. As a result, it is well suited to building modern, dynamic web applications.

One of Alpine.js major features is reactive data binding. Without needing manual updates or page refreshes, application developers may construct apps that automatically update and reflect changes in data. As a result, developing responsive, dynamic user interfaces that are simple to update and maintain is simple.

Declarative rendering is also supported by Alpine.js, which enables developers to specify how their application should appear and function instead of having to manually alter the user interfaces is made simple and requires little to no coding.

1

Why Alpine?

There are various reasons why developers might want to use alpine js for their projects or website,

  • With Alpine.js, you can get fast and efficient JavaScript development.

  • Reactive components can be easily implemented.

  • Developers can find its syntax intuitive and easy to learn.

  • You can integrate JavaScript libraries and frameworks.

  • Setup is quick and easy because it has a small footprint and does not require a build step.

you can learn more about Alpine.js on its documentation.

Advantages to using Alpine.js.

  • Lightweight and fast: Alpine.js has been created to be quick and light, with a small footprint and no external dependencies. This makes it the perfect option for creating interactive and flexible user interfaces without overburdening your program.

  • Easy to learn and use: Even developers without prior experience with JavaScript may quickly learn and utilize Alpine.js due to its straightforward declarative syntax.

  • Integrates well with other frameworks: Alpine.js is simple to combine with other frameworks and libraries since it is only a thin overlay over native browser APIs.

  • Support for common web development patterns: Common web development patterns, including reactive data binding, event handling, and component-based design, are supported by Alpine.js.

Alpine js vs. other JS frameworks

Alpine jsOther Frameworks
Alpine.js is a lightweight library that provides the essential features needed to build modern front-end applications.Other frameworks, such as React and Angular, are larger and provide a broader range of features but may be more complex to learn and use.
Alpine.js has built-in support for reactive data binding and composable components, which makes it easy to build interactive and responsive applications.Other frameworks may require additional libraries or tools to provide these features.
Alpine.js has a small footprint and is designed to be fast and efficient. This makes it well-suited for building applications that need to be responsive and performant.Other frameworks may be larger and require more resources to run, making them less suitable for certain types of applications.

Collections of Alpine js Attributes

  • x-data: x-data declares a new Alpine component and its data for a block of HTML
  • x-on: The x-on attribute listen for browser events on an element
  • x-model: x-model synchronize a piece of data with an input element
  • x-show: x-show toggle the visibility of an element
  • x-ignore: The x-ignore attribute prevents a block of HTML from being initialized by Alpine

Session Replay for Developers

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data. Check our GitHub repo and join the thousands of developers in our community.

Building a Simple To-do app with Alpine js

2

Now let us use Alpine.js to create a simple to-do application.

We can set it up using two methods

  • CDN: <script defer src="https://unpkg.com/alpinejs@3.10.5/dist/cdn.min.js"></script>
  • NPM: npm install alpinejs

Then, import Alpine.js into your project.

    import Alpine from 'alpinejs'
    
    window.Alpine = Alpine
    
    Alpine.start()

Using anyone works fine, But for this project, we will use the CDN method.

Building Todo App

<div
  x-data="{ todos: getTodosFromLocalStorage(), userInput: '' }"
  class="container"
>
  <form
    x-on:submit.prevent="if(userInput.trim().length) {
    todos.push({name: userInput, completed: false }); userInput = '';
    saveTodosToLocalStorage(todos);
  }"
  >
    <input
      x-model="userInput"
      placeholder="Enter todo item"
      type="text"
      class="input"
    />
    <button>Add</button>
  </form>
  <template x-for="todo in todos">
    <div>
      <input type="checkbox" x-model="todo.completed" />
      <span x-text="todo.name" :class="{'completed': todo.completed}"></span>
      <button
        @click="todos = todos.filter((currTodo) => currTodo !== todo); 
        saveTodosToLocalStorage(todos)"
        class="delete"
      >
        x
      </button>
    </div>
  </template>
  <button
    @click="todos = []; saveTodosToLocalStorage(todos)"
    x-show="todos.length"
  >
    Clear
  </button>
</div>

The x-data attribute on the div element specifies an object literal that will be used to store the component’s data. This object has two properties: todos, an array of to-do items, and userInput, a string representing the user’s input.

<form
  x-on:submit.prevent="if(userInput.trim().length)
        
      todos.push({name: userInput, completed: false }); userInput = ''"
></form>

The x-on specifies an expression to be performed when the form is submitted:submit property of the form element. This expression, in turn, adds a new task to the todos array and clears the userInput if the user’s input is not just whitespace.

<input
  x-model="userInput"
  placeholder="Enter todo item"
  type="text"
  class="input"
/>

The x-model attribute of the input element inside the form ties its value to the userInput data property.

<template x-for="todo in todos">
  <div>
    <input type="checkbox" x-model="todo.completed" />
    <span x-text="todo.name" :class="{'completed': todo.completed}"></span>
    <button
      @click="todos = todos.filter((currTodo) => currTodo !== todo)"
      class="delete"
    >
      x
    </button>
  </div>
</template>

A block of items is rendered for each item in the todos array by thex-for property of the template element, which iterates over the array. A div element with a checkbox, a span element with the to-do text, and a delete button make up each block. The x-model attribute of the input element links its checked value to the finished property of the currently selected to-do item. The x-text attribute of the span element links its text content to the name property of the active to-do item. It also contains a :class attribute that, if the finished property of the current to-do item is true, ties a completed class to its element. The @click attribute on the button element designates a JavaScript expression to be launched after clicking the button. In this instance, the expression removes the current to-do item from the todos array.

<button @click="todos = []" x-show="todos.length">Clear</button>

A JavaScript code to be executed when the button is pressed is specified by the @click property of the button element, which is outside of the template element. In this instance, the phrase essentially deletes all to-do items by setting the todos array to an empty array. Additionally, it has a JavaScript expression specified by the x-show property that determines whether the element is shown. In this instance, the element is only shown if the length of the todos array is non-zero.

Adding LocalStorage

3

 function getTodosFromLocalStorage() {
    const todos = localStorage.getItem('todos');
    return todos ? JSON.parse(todos) : [];
  }

  function saveTodosToLocalStorage(todos) {
    localStorage.setItem('todos', JSON.stringify(todos));
  }

In the above code, two functions are responsible for communicating with the localStorage object. The localStorage object is a component of the Web Storage API (known as the Storage API for the Web) that provides access to storage space available for the current page. The localStorage object is similar to cookies but with significantly more storage space and without being transmitted to the server with every request.

This method retrieves the value of the todo item from local storage by using a method called getTodosFromLocalStorage, which parses the value and provides it to you as an array of todo items. If there are no items in localStorage, then the method is supposed to return an empty array in the absence of any items.

To save an array of todo items, a stringified JSON object is created and stored in local storage with the key todos as part of the saveTodosToLocalStorage method. Todo items may be stored in the user’s local storage and can be retrieved and stored by the user at any time.

Conclusion

The purpose of this article was to provide you with information about Alpine js and to explain why it is valuable. As part of your learning experience, you also learned how to create a simple to-do app using Alpine JS.

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs and track user frustrations. Get complete visibility into your frontend with OpenReplay, the most advanced open-source session replay tool for developers.

OpenReplay