Call Now : +971523144541

Single Blog

  • Home
  • Create a Custom Accordion in LWC

Create a Custom Accordion in LWC

Admin September 2, 2024 0 Comments

Welcome, in this post we will learn you about how to create an custom accordion in LWC. The accordion will be animated, and we will have full control over it, The LWC default accordion is lack of the open one accordion at a time, So, I also, included that feature into it, and by customizing a little bit it will also be able to keep more than one accordion open.

Demo

For Demo how the actual Custom Accordion Section Will work, please click to see the demo

Table of Contents

First of all create a component named “customAccordion”. Now in this component there should be three files HTML, CSS, and JavaScript.
Now place the below code in respective file.  

HTML Code

Copy this HTML code and past it into your customAccordion.html”  file.  

				
					<template>
    <div class="container">
        <div class="custom-accordion">

            <!-- Loop Over the Accordion Data -->

            <template for:each={customAccordionData} for:item="item">
                <div key={item.id} class="single-accordion-section">

                    <!-- Accordion Button -->

                    <div onclick={toggleAccordionSection} class="custom-accordian_title slds-grid slds-grid_align-spread"
                        data-buttonid={item.id}>
                        <p>{item.title}</p>
                        <i class="fa-regular fa-angle-down"></i>
                    </div>

                    <!-- Accordion Data Section -->
                     
                    <div class="custom-accordian_content" data-section-id={item.id}>
                        <div class="custom-accordion_content-inner">
                            <p>{item.description}</p>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>
</template>
				
			

JavaScript Code

Copy this JavaScript code and past it into your customAccordion.js”  file.  

				
					import { LightningElement } from 'lwc';

export default class CustomAccordion extends LightningElement {

    //  Data For Accordion

    customAccordionData = [
        {
            id: 1,
            title: 'This is the Accordion One',
            description: 'This is the content of the accordion one. This accordion is build with LWC(Lightening web components). The accordion is fully custom, and you can also enhance it features.',
        },
        {
            id: 2,
            title: 'This is the Accordion Two',
            description: 'This is the content of the accordion two. This accordion is build with LWC(Lightening web components). The accordion is fully custom, and you can also enhance it features.',
        },
        {
            id: 3,
            title: 'This is the Accordion Three',
            description: 'This is the content of the accordion three. This accordion is build with LWC(Lightening web components). The accordion is fully custom, and you can also enhance it features.',
        },
        {
            id: 4,
            title: 'This is the Accordion Four',
            description: 'This is the content of the accordion four. This accordion is build with LWC(Lightening web components). The accordion is fully custom, and you can also enhance it features.',
        }
    ]

    // To Open the first Accordion open by default, we will use connected callback

    connectedCallback() {
        // Open the first accordion by default
        const firstAccordionId = this.customAccordionData[0].id;
        setTimeout(() => {
            const firstSection = this.template.querySelector('[data-section-id="' + firstAccordionId + '"]');
            const firstButton = this.template.querySelector('[data-buttonid="' + firstAccordionId + '"]');
            
            if (firstSection && firstButton) {
                firstSection.classList.add('slds-is-open');
                firstSection.style.maxHeight = firstSection.scrollHeight + "px";
                firstButton.classList.add('title-active');
                firstButton.querySelector('i').classList.add('fa-angle-up');
                firstButton.querySelector('i').classList.remove('fa-angle-down');
            }
        }, 0); // Ensure the DOM is fully loaded before applying the styles
    }

    // To toggle the Accordion Section

    toggleAccordionSection(event) {
        let buttonid = event.currentTarget.dataset.buttonid;
        let currentSection = this.template.querySelector('[data-section-id="' + buttonid + '"]');
        let currentButton = this.template.querySelector('[data-buttonid="' + buttonid + '"]');

        // Check if currentButton is not null before applying styles
       
        let allButtons = this.template.querySelectorAll('.custom-accordian_title');
        if (!currentSection.classList.contains('slds-is-open')) {
            let allSections = this.template.querySelectorAll('.custom-accordian_content');
            allSections.forEach(section => {
                section.classList.remove('slds-is-open');
                section.style.maxHeight = '0px';
            });
            allButtons.forEach(section => {
                section.classList.remove('title-active');
            });
            allButtons.forEach(button => {
                if (button.dataset.buttonid == buttonid) {
                    button.querySelector('i').classList.add('fa-angle-up');
                    button.querySelector('i').classList.remove('fa-angle-down');
                }
                else {
                    button.querySelector('i').classList.remove('fa-angle-up');
                    button.querySelector('i').classList.add('fa-angle-down');
                }
            });
            currentSection.classList.add('slds-is-open');
            currentSection.style.maxHeight = currentSection.scrollHeight + "px";
            currentButton.classList.add('title-active');

        } else {
            currentSection.classList.remove('slds-is-open');
            currentButton.classList.remove('title-active');
            currentSection.style.maxHeight = '0px';
            allButtons.forEach(button => {
                if (button.dataset.buttonid == buttonid) {
                    button.querySelector('i').classList.remove('fa-angle-up');
                    button.querySelector('i').classList.add('fa-angle-down');
                }
            });
        }
    }
}
				
			

CSS Code

Copy this CSS code and past it into your customAccordion.css”  file.  

				
					.container {
    width: 600px;
    max-width: 100%;
    margin: auto;
}

.custom-accordian_content {
    overflow: hidden;
    visibility: hidden;
    opacity: 0;
    max-height: 0;
    transition: max-height 0.3s ease-out;
}

.custom-accordian_content.slds-is-open {
    overflow: visible;
    visibility: visible;
    opacity: 1;
    transition: max-height 0.3s ease-out;
}

.custom-accordian_title {
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: .3s;
    border: 1px solid#626065;
    padding: 1rem;
    margin-bottom: 1rem;
    border-radius: 30px;
    background: #fff;
    z-index: 2;
    position: relative;
}

.custom-accordian_title.title-active {
    color: #fff;
    background: #ff3b00;
    border-color: #ff3b00;
    transition: .3s;
}

.custom-accordion .custom-accordian_content .custom-accordion_content-inner {
    padding: 1rem;
    padding-top: 0;
}
				
			

customAccordion.js-meta.xml file

Please make sure that your customAccordion.js-meta.xml” is exposed and have availability access to the respective enviornement where you are using the your compoennt. for reference you can check below code :

				
					<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>61.0</apiVersion>
    <isExposed>true</isExposed>
	<targets>
		<target>lightning__RecordPage</target>
		<target>lightning__AppPage</target>
		<target>lightning__HomePage</target>
		<target>lightning__Tab</target>
		<target>lightning__Inbox</target>
		<target>lightning__UtilityBar</target>
		<target>lightning__FlowScreen</target>
		<target>lightningSnapin__ChatMessage</target>
		<target>lightningSnapin__Minimized</target>
		<target>lightningSnapin__PreChat</target>
		<target>lightningSnapin__ChatHeader</target>
		<target>lightning__RecordAction</target>
		<target>lightningCommunity__Page</target>
		<target>lightningCommunity__Default</target>
		<target>lightningCommunity__Page_Layout</target>
		<target>lightningCommunity__Theme_Layout</target>
		<target>lightningStatic__Email</target>
		<target>analytics__Dashboard</target>
	</targets>
</LightningComponentBundle>
				
			

Conclusion

That’s it now your custom accordion will work like a magic. please check and leave a feedback in comment section. Thanks. Have fun. 

Leave Comment