Hooks for Alpine.js
Published on by Paul Redmond
The Alpine Hooks module is a collection of hooks for use with Alpine.js. This package contains a variety of hooks used to improve the developer experience (DX) for common Alpine tasks.
Been a while since I released something for @Alpine_JS , so here's a new package: alpine-hooks. Inspired by hooks in React, these magic functions provide some useful helpers that I find myself using in a tonne of projects. Check it out!https://t.co/FMTP9WO3tE
— Ryan Chandler (@ryangjchandler) June 6, 2023
At the time of writing this module has the following hooks:
-
$useHover()
- react to the mouse hovering over an element -
$useFocus()
- react to an element being focused and blurred -
$useHash()
- update and react to changes towindow.location.hash
-
$useWindowSize()
- returns the window width and height and react to changes to window size
Here's an example of $useHover()
from the examples folder on GitHub:
<div x-data="{ hovering: $useHover($refs.target) }" class="py-8"> <div class="w-52 h-64 rounded bg-red-500 transition-colors ease-in-out duration-300 mx-auto flex items-center justify-center" x-bind:class="{ 'bg-red-500': !hovering, 'bg-blue-500': hovering }" x-ref="target" > <p class="font-medium" x-text="hovering ? 'Hovering...' : 'Not hovering...'"></p> </div></div>
You can install this package in your project with npm
:
npm install @ryangjchandler/alpine-hooks
You can learn more about this package, get full installation instructions, and view the source code on GitHub.