Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It’s great for quickly adding interactivity to any static HTML element.

You can turn any element into an “Alpine component” simply by adding the x-data attribute.

Imagine a drop-down menu like so:

  <div>
    <button>Toggle menu</button>
    <div>
      Menu item 1…
      Menu item 2…
      etc…
    </div>
  </div>
Without JS, everything would be visible at all times.

You’d make this reactive with Alpine like this:

  <div x-data=“menuVisible = false”>
    <button @click=“menuVisible = !menuVisible”>Toggle menu</button>
    <div x-cloak x-show=“menuVisible” x-transition @click.outside=“menuVisible = false”>
      Menu item 1…
      Menu item 2…
      etc…
    </div>
  </div>
When the button is clicked, the menu opens (or closes). x-transition adds a smooth fade effect, @click.outside hides the menu when clicked away from the element, and x-cloak prevents it from appearing before the DOM has fully loaded.

Those are just a few of the most common Alpine directives. It doesn’t try to do everything, just the basics simply and efficiently.

I use it for most projects now.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: