Add Alpine.js to Phoenix
By using LiveView we can normaly avoid the use of JavaScript. But sometimes a bit of additional JavaScript adds a nice touch to the user experience (e.g. collapse of a navigation menu). For this I prefer to use Alpine.js which is a lightweight and easy to use JavaScript framework.
Do you prefer video tutorials? Find this recipe at "Add Alpine js to Phoenix in 60 seconds" in our @elixir-phoenix-ash YouTube Channel. |
Setup Phoenix
Let’s start by creating a new basic Phoenix app:
mix phx.new example_app --no-ecto
cd example_app
Install Alpine.js
cd assets && yarn add alpinejs && cd ..
For npm use cd assets && npm install alpinejs && cd .. instead. |
Configure app.js
Add the following to the top import
section of the assets/js/app.js
:
import Alpine from "alpinejs";
window.Alpine = Alpine;
Alpine.start();
And update the let liveSocket
part to:
let liveSocket = new LiveSocket("/live", Socket, {
longPollFallbackMs: 2500,
params: { _csrf_token: csrfToken },
dom: {
onBeforeElUpdated(from, to) {
if (from._x_dataStack) {
window.Alpine.clone(from, to);
}
},
},
});
Test if Alpine.js works
Open lib/example_app_web/controllers/page_html/home_html.heex
and replace its content with the following Alpine.js example code:
<div x-data="{ count: 0 }" class="flex items-center justify-center min-h-screen">
<button
x-on:click="count++"
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
>
Increment
</button>
<span x-text="count" class="ml-4"></span>
</div>
Start the Phoenix server:
mix phx.server
Open your browser and navigate to http://localhost:4000
. You should see a button and a number that increments when you click the button.