Lightning Web Component Accordion

Let us discuss here how to create an Accordion using the Lightning Web Component lightning-accordioncomponent. A lightning-accordion component groups related content in a single container. Only one accordion section is expanded at a time. When you select a section, it’s expanded or collapsed. Each section can hold one or more Lightning components. To create Lightning web component we need to SFDX. Please refer this link for Environment setup for development. 

1.Create an apex class 

Now create an apex class to get the data from the Salesforce. here we will be fetching the accounts and its contacts data and will be displaying them like an accordion.

use this SFDX command to create an apex class

sfdx force:apex:class:create -n GetAccountContactData -d force-app/main/default/apex

Here is the complete code

public with sharing class GetAccountContactData {
    public static List<Account> getAccountData() {
        return [SELECT Id, Name ,(Select Id ,Name from Contacts) from Account];


2. Create a Lightning Web Component 

Create a lightning web component that will show the accordion. run the following SFDX command to create a lightning web component.

sfdx force:lightning:component:create --type lwc -n AccordionEx -d force-app/main/default/lwc

Here is the code for the AccordionEx web component.

Here is the AccordionEx.html code that will display the Accordion.

    <h6>Accoridan Exmape v8</h6>

    <lightning-accordion allow-multiple-sections-open={multiple}>
        <template if:true={accounts}>
            <template for:each={accounts} for:item="acc">
                <lightning-accordion-section name={acc.Name} label={acc.Name} key={acc.Id}>
                    <template for:each={acc.Contacts} for:item="con">
                        <lightning-accordion-section name={con.Name} label={con.Name} key={con.Id}>


Here is the AccordionEx.js JavaScript controller class.

import {LightningElement,api,wire,track} from 'lwc';
import getAccountData from '@salesforce/apex/GetAccountContactData.getAccountData';

export default class AccordionEx extends LightningElement {
@track multiple = true;
@track accounts ;
}) {
    if (data) {
        this.accounts = data;
        console.log(JSON.stringify(data, null, '\t'));
        data.forEach(function (item, key) {
    } else if (error) {
        this.error = error;


Here is the AccordionEx.js-meta.xml configuration file which allows us to add this component to the record page.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="">


3.Push changes

Now push the changes to scratch org using this below SFDX command

sfdx force:source:push

Now after pushing the changes to add this lightning web component to the record page. Go to the lightning app builder and add this component to the record page and save it .which will be displayed similar accordion on the record page.