How to Create SPFx Web Part with jQuery Accordion

Do you ever need to display information in an accordion style on the SharePoint home page? Recently, for a client, we developed a client-side SPFx web part that dynamically displays information from a SharePoint events list.

Even though SharePoint already has an Events web part to display upcoming events, it didn’t provide the flexibility we wanted. That’s why we built a custom accordion-style web part using SPFx and JQuery, so users could click and expand each event to see all the details easily, without leaving the page.

In this article, I will explain how to create an SPFx web part with a jQuery accordion.

What is the jQueryUI accordion?

The jQuery UI Accordion is an expandable and collapsible container for content sections. It looks like a list of headings, and when you click one, the related content opens. If you click another heading, the previous one closes. So it helps you show a lot of information in a small, organized space.

There are two ways to use the jQuery UI Accordion:

  1. We can turn any HTML block into an accordion by calling:
$(selector).accordion(options);

Here, options is an object that specifies how the accordion should look and behave. For exe:

  • Which panel should open first?
  • Should panels be collapsible?
  • Should they auto-adjust height?
  1. Once the accordion is created, you can run actions like open, close, enable, or disable.
$(selector).accordion("action", params);
  • “disable” will disable the accordion.
  • “option”, “active”, 1 = opens the second panel, etc.

Now, let me show you how to use jQuery accordion in a SharePoint framework web part.

SPFx Web Part with jQueryUI Accordion

In the example below, you can see the jQuery accordion control in the SPFx web part displaying all the timings. When you click on a particular time, it shows the topic to be explained, the speaker, where it is being conducted, and some information about the topic.

jquery accordion in spfx web part

For this SPFx web part, the following is the SharePoint list I used to store the event details.

jquery accordion example

This SharePoint list contains the following fields:

Column NameData Type
TitleDefault field
TimeSlotSingle line of text
SpeakerSingle line of text
RoomSingle line of text
DescriptionMultiple lines of text
TrackChoice

I hope you know how to create an SPFx web part; if not, check out this article. While creating an SPFx web part, choose “No framework” as the framework.

  1. Run the command below in the Terminal pane or in the command prompt where your solution is opened. This installs the jQuery NPM package.
npm install jquery@2
  1. Then run the command below to install the jQuery UI NPM package.
npm install jqueryui
  1. Next, we need to install the TypeScript type declarations for our web part. Run the following commands.
npm install @types/jquery@2 --save-dev
npm install @types/jqueryui --save-dev
  1. Open config.json and update the “externals”:{} section as shown below so that it doesn’t include the jQuery and jQuery UI bundles. This will reduce the file size while bundling.
{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
  "version": "2.0",
  "bundles": {
    "jquery-accordion-web-part": {
      "components": [
        {
          "entrypoint": "./lib/webparts/jqueryAccordion/JqueryAccordionWebPart.js",
          "manifest": "./src/webparts/jqueryAccordion/JqueryAccordionWebPart.manifest.json"
        }
      ]
    }
  },
  "externals": {
     "jquery": "node_modules/jquery/dist/jquery.min.js",
    "jqueryui": "node_modules/jqueryui/jquery-ui.min.js"
  },
  "localizedResources": {
    "JqueryAccordionWebPartStrings": "lib/webparts/jqueryAccordion/loc/{locale}.js"
  }
}
  1. Now open the .ts file where the accordion web part code needs to be written. Then, replace your default code with the code below.
import { Version } from '@microsoft/sp-core-library';
import {
  type IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import type { IReadonlyTheme } from '@microsoft/sp-component-base';
import styles from './JqueryAccordionWebPart.module.scss';
import * as strings from 'JqueryAccordionWebPartStrings';
import * as $ from 'jquery';
import 'jqueryui';
import 'jquery-ui-dist/jquery-ui.css';
export interface IJqueryAccordionWebPartProps {
  description: string;
}
interface IEventSessionItem {
  Title: string;
  TimeSlot: string;
  Speaker: string;
  Room: string;
  Description: string;
 Id: number; 
}

export default class JqueryAccordionWebPart extends BaseClientSideWebPart<IJqueryAccordionWebPartProps> {

 public render(): void {
    this.domElement.innerHTML = `
      <div class="${styles.accordionContainer}">
      <h2 class="accordionHeading">🎤 Event Session Planner</h2>
      <div id="accordion"></div>
      </div>
    `;
    this._loadAccordionData();
  }
private _loadAccordionData(): void {
const listUrl = `${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('EventSessions')/items`;

    fetch(listUrl, {
      headers: {
        "Accept": "application/json;odata=nometadata"
      }
    })
      .then(response => response.json())
      .then((data: { value: IEventSessionItem[] })=> {
          if (!data || !data.value) {
          console.error("EventSessions list returned no data");
          return;
        }
        let html = "";

        data.value.forEach((item: IEventSessionItem) => {
          html += `
            <h3>${item.TimeSlot}</h3>
            <div>
              <p><strong>${item.Title}</strong></p>
              <p><strong>Speaker:</strong> ${item.Speaker}</p>
              <p><strong>Room:</strong> ${item.Room}</p>
              <p>${item.Description}</p>
            </div>
          `;
        });
        const accordionDiv = this.domElement.querySelector("#accordion");
        if (accordionDiv) {
          accordionDiv.innerHTML = html;
        }
        this._initAccordion();
      })
      .catch(error => {
        console.error("Error loading EventSessions list:", error);
      });
  }
private _initAccordion(): void {
    const accordionDiv: any = $("#accordion", this.domElement);
    accordionDiv.accordion({
      collapsible: true,
      heightStyle: "content",
      active: false
    });
  }

  protected onInit(): Promise<void> {
    return Promise.resolve();
  }

  protected onThemeChanged(currentTheme: IReadonlyTheme | undefined): void {
    if (!currentTheme) {
      return;
    }
    const {
      semanticColors
    } = currentTheme;

    if (semanticColors) {
      this.domElement.style.setProperty('--bodyText', semanticColors.bodyText || null);
      this.domElement.style.setProperty('--link', semanticColors.link || null);
      this.domElement.style.setProperty('--linkHovered', semanticColors.linkHovered || null);
    }

  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

Let’s understand the code now:

  • At the beginning, we imported the BaseClientSideWebPart, along with jQuery and jQuery UI. Also imported jQuery UI CSS, so we don’t need CDN references.
  • IEventSessionItem = We created this interface to define the SharePoint list item.
  • In the render() method, we created an HTML structure. A container <div id=”accordion”></div> is added where the jQuery UI accordion will be applied. It calls _loadAccordionData() to bring dynamic data from SharePoint.
  • _loadAccordionData() = Here, we built a REST API URL to fetch items from the EventSessions list. Within this, for each SharePoint item, we added an <h3> element for an accordion header and a <div> element for an accordion content, which matches the jQuery UI Accordion requirements.
  • Then, the generated HTML is injected into the #accordion container and also calls the _initAccordion() method.
  • _initAccordion() = In this method, we set up the jQuery UI accordion with:
    • collapsible: true = all panels can close.
    • heightStyle: “content” = height adjusts automatically.
    • active: false = all sections collapsed initially.
  1. Apply the styles to this web part by updating the .SCSS file.
@import '~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss';
.accordionContainer {
  margin: 20px 0;
.accordionHeading {
    font-size: 26px;
    font-weight: 600;
    margin-bottom: 15px;
    color: #333;
    font-family: "Segoe UI", Arial, sans-serif;
    border-bottom: 2px solid #ccc;
    padding-bottom: 6px;
  }

  #accordion {
    width: 600px;
    font-family: Arial, Helvetica, sans-serif;

    .ui-accordion-header {
      background: #e6e6e6;
      border: 1px solid #ccc;
      padding: 10px;
      margin-top: 5px;
      font-size: 16px;
      cursor: pointer;
      font-weight: bold;
    }

    .ui-accordion-header:hover {
      background: #dcdcdc;
    }

    .ui-accordion-content {
      border: 1px solid #ccc;
      border-top: none;
      padding: 10px;
      font-size: 14px;
    }

    .ui-accordion-header-icon {
      margin-right: 10px;
    }
  }
}
  1. Save the changes and run the gulp serve command to test it locally in the workbench. If it is working fine, run the commands below to build the package, then upload those solutions to the tenant or site collection app catalog, depending on your requirements.
gulp clean
gulp build
gulp bundle --ship
gulp package-solution --ship

This way, you can easily use the jQuery Accordion control in the SPFx web part to display the SharePoint list items dynamically.

I hope you found this article helpful! In this tutorial, I explain how to use the jQuery Accordion control to dynamically display SharePoint list items in a SharePoint Framework web part. Download and try this solution once on your end, and make sure to update the SharePoint list name in the code if it differs.

You may also like the following tutorials:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App