Accordion in Salesforce Lightning Web Components

In Salesforce Lightning Web Components, we have a built-in feature to create an accordion component using lightning-accordion. By creating an accordion in Lightning web components, we can expand and collapse content sections to organise the data.

In this Salesforce tutorial, we will learn about the lightning-accordion feature and how to add an accordion in Salesforce Lightning Web Components.

What is Salesforce Lightning Accordion?

In Salesforce, we have an inbuilt component to add an accordion in the LWC components, which is ‘lightning-accordion’. The lightning-accordion component in LWC is a container that holds multiple ‘lightning-accordion-section’ components, and each section can be expanded or collapsed by clicking its header.

Attributes for Lightning Accordion:

The Lightning Accordion has attributes, which are details we add to tags in a “name: value” format. Both “lightning-accordion” and “lightning-accordion-section” have some attributes that are mentioned below.

Lightning Accordion Attributes:

  • active-section-name: This feature expands specified accordion sections by taking a string for a single section or a list of section names.
  • allow-multiple-sections-open: This allows expanding multiple sections within the same component. If not used, then we can only expand a single section, like when you expand another section, the current one will be closed.
  • title – It displays the text when we hover on the element.

Lightning Accordion Section Attributes:

  • label- The text that displays as the title of the section.
  • name- The unique section name to use with the active-section-name attribute in the accordion component.

Add Lightning Accordion in Lightning Web Components

There are two ways to add an accordion in the Lightning Web Components.

  • Accordion with a Single Active Section
  • Accordion with Multiple Active Sections

Accordion With a Single Active Section in LWC Component

In this example, we will create an accordion with three sections and set one section to be active (expanded) by default. When we click on another section to expand it, the current one will be closed.

Follow the steps below to add an accordion with a single active section in the LWC component.

  1. Create an LWC component and enter the code below in an HTML file. We have defined the sections using a lightning accordion.
<template>
    <lightning-card title="Accordion with Single Active Section" icon-name="utility:accordion">
        <div class="slds-p-around_medium">
            <lightning-accordion active-section-name="s