Home / Snippets / Build Nested Collpsing Component in Alpine Js Using Collapse Plugin
Build Nested Collpsing Component in Alpine Js Using Collapse Plugin cover

Build Nested Collpsing Component in Alpine Js Using Collapse Plugin

1.4K

3 years ago

0 comments

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

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this