- Published
- Author
- Nitturu BabaSystem Analyst
π Using Alpine.js in Rails to Toggle Content Efficiently
You can use Alpine.js in a Rails app to handle simple UI interactions like showing, hiding, or toggling content β with zero overhead and great maintainability.
π§ How it works:
β’ Alpine adds lightweight reactivity directly in your HTML using attributes like
β’ Clicking a button updates the
β’ Alpine automatically re-evaluates all
β’ It then updates the UI by toggling styles like
β’ On clicking the "Urgent" button, Alpine applies
π‘ Example in Rails ERB:
β’ Both partials are rendered server-side on initial load
β’ Alpine just toggles their visibility using CSS (e.g.,
β’ No data loss or performance bottleneck β ideal for UI tab switching or inline modals
β Why it's great:
β’ No page reloads or re-renders
β’ No JavaScript DOM manipulation β just CSS toggling
β’ Preserves state and DOM structure
β’ Ideal for tabs, modals, section toggles, and lightweight UI
#Rails #Alphine.js
You can use Alpine.js in a Rails app to handle simple UI interactions like showing, hiding, or toggling content β with zero overhead and great maintainability.
π§ How it works:
β’ Alpine adds lightweight reactivity directly in your HTML using attributes like
x-data, @click, and x-show.β’ Clicking a button updates the
type (or any reactive) value.β’ Alpine automatically re-evaluates all
x-show (and related) bindings when that reactive value changes.β’ It then updates the UI by toggling styles like
display: none, not by re-rendering or manipulating the DOM.β’ On clicking the "Urgent" button, Alpine applies
display: none to the normal_partial and removes it from urgent_partial, effectively toggling visibility between the two.π‘ Example in Rails ERB:
Code
<div x-data="{ type: 'normal' }">
<button @click="type = 'normal'">Normal</button>
<button @click="type = 'urgent'">Urgent</button>
<div x-show="type === 'normal'">
<%= render "normal_partial" %>
</div>
<div x-show="type === 'urgent'">
<%= render "urgent_partial" %>
</div>
</div>β’ Both partials are rendered server-side on initial load
β’ Alpine just toggles their visibility using CSS (e.g.,
display: none), it wont manipulate DOM.β’ No data loss or performance bottleneck β ideal for UI tab switching or inline modals
β Why it's great:
β’ No page reloads or re-renders
β’ No JavaScript DOM manipulation β just CSS toggling
β’ Preserves state and DOM structure
β’ Ideal for tabs, modals, section toggles, and lightweight UI
#Rails #Alphine.js