Skip to content

Instantly share code, notes, and snippets.

@michelmany
Created November 5, 2021 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michelmany/1216d3341870638a114d604987db5fde to your computer and use it in GitHub Desktop.
Save michelmany/1216d3341870638a114d604987db5fde to your computer and use it in GitHub Desktop.
Alpine.js Accordion Component
<div x-data="{ active: 1 }" class="space-y-4">
<div x-data="{
id: 1,
get expanded() {
return this.active === this.id
},
set expanded(value) {
this.active = value ? this.id : null
},
}" role="region" class="border border-black">
<h2>
<button
@click="expanded = !expanded"
:aria-expanded="expanded"
class="flex items-center justify-between w-full font-bold text-xl px-6 py-3"
>
<span>Question #1</span>
<span x-show="expanded" aria-hidden="true" class="ml-4">&minus;</span>
<span x-show="!expanded" aria-hidden="true" class="ml-4">&plus;</span>
</button>
</h2>
<div x-show="expanded" x-collapse>
<div class="pb-4 px-6">Lorem ipsum dolor sit amet consectetur adipisicing elit. In magnam quod natus deleniti architecto eaque consequuntur ex, illo neque iste repellendus modi, quasi ipsa commodi saepe? Provident ipsa nulla earum.</div>
</div>
</div>
<div x-data="{
id: 2,
get expanded() {
return this.active === this.id
},
set expanded(value) {
this.active = value ? this.id : null
},
}" role="region" class="border border-black">
<h2>
<button
@click="expanded = !expanded"
:aria-expanded="expanded"
class="flex items-center justify-between w-full font-bold text-xl px-6 py-3"
>
<span>Question #2</span>
<span x-show="expanded" aria-hidden="true" class="ml-4">&minus;</span>
<span x-show="!expanded" aria-hidden="true" class="ml-4">&plus;</span>
</button>
</h2>
<div x-show="expanded" x-collapse>
<div class="pb-4 px-6">Lorem ipsum dolor sit amet consectetur adipisicing elit. In magnam quod natus deleniti architecto eaque consequuntur ex, illo neque iste repellendus modi, quasi ipsa commodi saepe? Provident ipsa nulla earum.</div>
</div>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment