Accordion is a very frequent requirement in SPFx web parts. There are various npm packages available for implementing this.

In this article, we will explore implementing expand / collapse functionality in SPFx using plain JavaScript. Although the implementation is with plain JavaScript, it can also be used with React based implementation.


Develop SPFx Solution

Let us develop the SPFx web part as shown below,

In the solution, create a model at src\webparts\expandCollapse\IAnnouncementItem.ts to represent an Announcement item.

In the web part, implement a method to read announcements. For simplicity, I am using mock method to return dummy announcements.

The above FAQs are taken from Microsoft Frequently Asked Questions page.

Update the render method to display the announcements.

In the enableExpandCollapse method, we use setInterval to evaluate the existence of an element with className collapsible and add click event to an individual button to expand/collapse a specific div next to it.

The getAnnouncementDetails method will return the HTML structure for announcements to render.

The _setButtonEventHandlers method will register the event handlers for Expand/collapse buttons,

In the expandAll method, we are expanding all the divs using CSS style of display block, as clicked.

In the collapseAll method, we are collapsing all the divs using CSS style of display none, as clicked.

Accordion in an action

When deployed, the web part works as below:


A common requirement of expand/collapse (Accordion) functionality can be implemented using plain JavaScript in SPFx. As well, there are various third party npm packages available for this functionality.