With Alpine.js
Since Enhance renders “just” HTML, you can use other tools that work with vanilla HTML. Alpine.js is a minimal, but powerful, framework for adding interactivity to your application without writing much actual JavaScript.
This approach can be used to leverage similar libraries, like htmx. Though, you may find that your project doesn’t need them once you’ve learned all of Enhance’s features.
Simple collapse example
Here’s a modified version of Alpine’s “dropdown” example from the Alpine “Start here” doc.
We’ve wrapped it in an Enhance component, added an unnamed <slot>
, and included the CDN version of Alpine.js.
export default function SectionCollapse ({ html }) {
return html`
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<div x-data="{ open: false }">
<button @click="open = !open">
<span x-show="!open">👉</span>
<span x-show="open">👇</span>
</button>
<div x-show="open" @click.outside="open = false">
<slot></slot>
</div>
</div>
`
}
Eventually, you may want to bundle Alpine.js into your application.
Try out Enhance’s @bundles
feature.
This component can now be used from any HTML page in your Enhance application.
<main>
<h1>Alpine.js Test</h1>
<section-collapse>
<!-- This will be rendered to the component <slot> -->
<p>Hey, check that out!</p>
</section-collapse>
</main>