Posts Learn Components Snippets Categories Tags Tools About
/

Build Nested Collpsing Component in Alpine Js Using Collapse Plugin

Get started with alpine js collapse plugin to build nested collapsible component

Created on Sep 29, 2021

1380 views

Recently alpine js just released the collapse plugin and this plugin "allows you to expand and collapse elements using smooth animations". In this short snippet, you will learn how to build a nested collapsing component using the collapse plugin.

Include Alpine JS Collapse Plugin


For this example, we'll be using the CDN for the collapse plugin so add the following code to your head tag otherwise use the NPM to install it to your project.
<!-- Alpine Plugins -->
<script defer src="https://unpkg.com/@alpinejs/[email protected]/dist/cdn.min.js"></script>
 
<!-- Alpine Core -->
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>

Crate Nested Collapsing Component


To create a nested component that is also collapsable, you can define another Alpine JS data and specify the same property as the parent. component. By doing so the nested component will also be toggleable which makes the sub-component have its own state. So in order to toggle the innermost component, you will have to toggle it twice. Do refer to the code below for the full example.
<div x-data="{ expanded: false }">
    <button @click="expanded = ! expanded">Toggle Content</button>
 
    <div x-show="expanded" x-collapse>
      <p>Content Here</p>
      
      <div x-data="{ expanded: false }">
        <button @click="expanded = ! expanded">Toggle Content</button>

          <p x-show="expanded" x-collapse>nested content here</p>
      </div>
    </div>
</div>
When content is opend yoou will be able to see the sub toggle content

Toggling the sub content will open the content like in the screenshot above

Do note that since the behavior and implementation differ from Alpine's standard transition system, this functionality was made into a dedicated plugin by the Alpine Js team.

Other Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)