Introduction
Accordion menus and widgets are widely used on websites to manage a large amount of content and navigation lists. In this article, we will see step by step implementation of the accordion with SharePoint list.
Scenario
In this example, we will create a list called "Accordion" and in the list, we will create a Description field (it will be multiple lines of text -Rich text) and will use Title and Description field to expand and collapse.
We will use PnPJs to get list items and then will render them in the accordion form.
At the end, our output will be like this,
Let's see the step-by-step implementation.
Implementation
- Create a list with Title and Description fields as mentioned above.
- Open a command prompt
- Move to the path where you want to create a project
- Create a project directory using:
- md directory-name
Move to the above-created directory using:
- cd directory-name
Now execute the below command to create an SPFx solution:
- yo @microsoft/sharepoint
It will ask some questions, as shown below,
After a successful installation, we can open a project in any source code tool. Here, I am using the VS code, so I will execute the command:
- code .
Now we will install pnpjs and pnp-spfx-controls-react as shown below:
- npm install @pnp/sp --save
- npm install @pnp/spfx-controls-react --save --save-exact
Now go to the src > webparts > webpart > components > I{webpartname}Props.ts file,
- import { WebPartContext } from "@microsoft/sp-webpart-base";
- export interface IPnpReactAccordionProps {
- description: string;
- listName: string;
- context: WebPartContext;
- }
- interface IListItem {
- Id?: string;
- Title: string;
- Description: string
- }
- export interface IPnpReactAccordionState {
- listItems: IListItem[];
- errorMessage: string;
- }
Create a Service folder inside src and then in this folder create a file called SPService.ts. And in this file, we will create a service to get list items as below,
Here list name will come from the webpart property pane.
- import { WebPartContext } from "@microsoft/sp-webpart-base";
- import { sp } from '@pnp/sp/presets/all';
- export class SPService {
- constructor(private context: WebPartContext) {
- sp.setup({
- spfxContext: this.context
- });
- }
- public async getListItems(listName: string) {
- try {
- let listItems: any[] = await sp.web.lists.getByTitle(listName)
- .items
- .select("Id,Title,Description")
- .get();
- return listItems;
- } catch (err) {
- Promise.reject(err);
- }
- }
- }
Now move to the {webpartname}Webpart.ts. And create a list name property in property pane configuration and pass context and list name property as below,
- import * as React from 'react';
- import * as ReactDom from 'react-dom';
- import { Version } from '@microsoft/sp-core-library';
- import {
- IPropertyPaneConfiguration,
- PropertyPaneTextField
- } from '@microsoft/sp-property-pane';
- import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
- import * as strings from 'PnpReactAccordionWebPartStrings';
- import PnpReactAccordion from './components/PnpReactAccordion';
- import { IPnpReactAccordionProps } from './components/IPnpReactAccordionProps';
- export interface IPnpReactAccordionWebPartProps {
- description: string;
- listName: string;
- }
- export default class PnpReactAccordionWebPart extends BaseClientSideWebPart<IPnpReactAccordionWebPartProps> {
- public render(): void {
- const element: React.ReactElement<IPnpReactAccordionProps> = React.createElement(
- PnpReactAccordion,
- {
- description: this.properties.description,
- listName: this.properties.listName,
- context: this.context
- }
- );
- ReactDom.render(element, this.domElement);
- }
- protected onDispose(): void {
- ReactDom.unmountComponentAtNode(this.domElement);
- }
- 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
- }),
- PropertyPaneTextField('listName', {
- label: strings.ListNameFieldLabel
- })
- ]
- }
- ]
- }
- ]
- };
- }
- }
Move to the {webpartname}.tsx file and then bind the service using current context and the call service for get list items and set values in the state and render it in accordion control as below,
- import * as React from 'react';
- import styles from './PnpReactAccordion.module.scss';
- import { IPnpReactAccordionProps } from './IPnpReactAccordionProps';
- import { IPnpReactAccordionState } from './IPnpReactAccordionState';
- import { escape } from '@microsoft/sp-lodash-subset';
- import { SPService } from '../../../Service/SPService';
- import { Accordion } from "@pnp/spfx-controls-react/lib/Accordion";
- export default class PnpReactAccordion extends React.Component<IPnpReactAccordionProps, IPnpReactAccordionState> {
- private _services: SPService = null;
- constructor(props: IPnpReactAccordionProps) {
- super(props);
- this.state = {
- listItems: [],
- errorMessage: ''
- }
- /** Bind service using current context */
- this._services = new SPService(this.props.context);
- }
- public componentDidMount() {
- this.getListItems();
- }
- /** Get items of selected list and set values in state */
- private async getListItems() {
- if (this.props.listName) {
- let items = await this._services.getListItems(this.props.listName);
- this.setState({ listItems: items });
- }
- else {
- this.setState({ errorMessage: 'Please enter the list name in property pane configuration.' });
- }
- }
- public render(): React.ReactElement<IPnpReactAccordionProps> {
- return (
- <div className={styles.pnpReactAccordion}>
- {
- //Map list items and render in accordion
- (this.state.listItems && this.state.listItems.length) ? this.state.listItems.map((item, index) => (
- <Accordion title={item.Title} defaultCollapsed={true} className={"itemCell"} key={index}>
- <div className={"itemContent"}>
- <div className={"itemResponse"} dangerouslySetInnerHTML={{ __html: item.Description }}></div>
- </div>
- </Accordion>
- )) : <p>{this.state.errorMessage}</p>
- }
- </div>
- );
- }
- }
Now serve the application using the below command,
- gulp serve
Now test the webpart in SharePoint-SiteURL + /_layouts/15/workbench.aspx.
Output

Find the full source code here.
Summary
In this article, we have seen how to use accordion control with the SharePoint list.
I hope this helps.
Sharing is caring!!

Yang MasonPosted May 26, 2021, 5:24 AM
I am studying recently SPFx and PnP. You article is very helpful to me . thank youfor sharing.
Vinay AyinapurapuPosted Apr 23, 2021, 2:28 PM
Nice one chandani