How to Create an Accordion with Alpine JS

For this we use the official Alpine JS plugin x-collapse. However, you don't have to use this, it is possible to recreate the effect with the following:

  • Add maxHeight value to x-data
x-data="{ activeAccordion: false, maxHeight: 0 }"
  • Add an x-init on the same element as x-data
x-init="maxHeight = `${$refs.accordionContent.scrollHeight}px`"
  • On each accordion content element add x-ref="accordionContent"
  • On that same element add the styling
:style="activeAccordion && { 'max-height': maxHeight }"

And that's it, I can add an example if need be. However, here's the much cleaner approach using x-collapse.

Created by Mark Mead