Skip to content

Accordion Component

React

Headless UI for React

headlessui.dev/react/disclosure

WordPress

Includes code for WordPress using ACF Pro plugin.

Add a Repeater field, in this example "our_people".

<div class="grid">

  <?php
    if( have_rows('our_people') ):
      while ( have_rows('our_people') ) : the_row();
  ?>

    <div class="md:col-span-6 lg:col-span-4 xl:col-span-3">

      <button class="accordion-button">
        <h3><?php the_sub_field('name'); ?></h3>
      </button>
      <div class="accordion-content accordion-content--closed">
        <?php the_sub_field('description'); ?>
      </div>

    </div>

  <?php
      endwhile;
    endif;
  ?>

</div>

CSS:

/*--------------------------------------------------------------
# Accordion
--------------------------------------------------------------*/

.accordion-button {
  @apply w-full text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-black focus-visible:ring-offset-2 ring-opacity-50;
}

.accordion-button.active h3:after {
  @apply rotate-[-225deg];
}

.accordion-button h3:after {
  @apply text-[24px] md:text-[26px] 2xl:text-[38px] leading-tight;
  @apply float-right transition-transform duration-500 text-black;
  content: "+";
}

.accordion-content {
  @apply overflow-hidden;
  transition: max-height .5s;
}

.accordion-content.accordion-content--closed {
  @apply max-h-0;
}

JavaScript:

<script>
  var acc = document.getElementsByClassName("accordion-button");
  var i;

  for (i = 0; i < acc.length; i++) {

    acc[i].onclick = function() {

      var panel = this.nextElementSibling;

      if (panel.style.maxHeight) {
        // close the panel
        this.classList.toggle("active");
        panel.style.maxHeight = null;
      } else {
        // open the panel
        this.classList.toggle("active");
        panel.style.maxHeight = panel.scrollHeight + "px";
      }
    };
  }
</script>

Other implementations