Getting started with Alpine.js
Tags: alpine, webdev, javascript
Published: 2023-02-08 01:43:34


by [Nweke Emmanuel Manuchimso](https://blog.openreplay.com/authors/nweke-emmanuel-manuchimso)


Using [Alpine.js](https://alpinejs.dev/start-here), 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](https://alpinejs.dev/start-here) 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](https://alpinejs.dev/start-here), 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](https://blog.openreplay.com/images/getting-started-with-alpine-js/images/image01.png)

## Why [Alpine](https://alpinejs.dev/start-here)?

There are various reasons why developers might want to use [alpine js](https://alpinejs.dev/start-here) for their projects or website,


- With [Alpine.js](https://alpinejs.dev/start-here), 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](https://alpinejs.dev/) on its [documentation.](https://alpinejs.dev/start-here)*

### Advantages to using Alpine.js.

* Lightweight and fast: [Alpine.js](https://alpinejs.dev/) 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](https://alpinejs.dev/) 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](https://alpinejs.dev/).

## Alpine js vs. other JS frameworks
| Alpine js                                                                                                                                                                | Other 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](https://alpinejs.dev/directives/data):  `x-data` declares a new Alpine component and its data for a block of HTML
- [x-on](https://alpinejs.dev/directives/on): The `x-on`  attribute listen for browser events on an element
- [x-model](https://alpinejs.dev/directives/model): `x-model` synchronize a piece of data with an input element
- [x-show](https://alpinejs.dev/directives/show): `x-show` toggle the visibility of an element
- [x-ignore](https://alpinejs.dev/directives/ignore): The `x-ignore` attribute prevents a block of HTML from being initialized by Alpine



<h2>Session Replay for Developers</h2> 
<p><em>
Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data
</em></p>
<img alt="OpenReplay" width="768" height="400" src="https://blog.openreplay.com/assets/overview_Z17Qdyg.png" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em>






## Building a Simple To-do app with Alpine js

![2](https://blog.openreplay.com/images/getting-started-with-alpine-js/images/image02.gif)

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


We can [set it up](https://alpinejs.dev/essentials/installation) 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.

```javascript
    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

```html
<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.
            
```html
<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.

```html
<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.


```html
<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 the`x-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.


```html
<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](https://blog.openreplay.com/images/getting-started-with-alpine-js/images/image03.png)

```javascript
 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.


[![newsletter](https://blog.openreplay.com/newsletter_Z1P0UIP.png)](https://newsletter.openreplay.com/)