How To Use PnP React Accordion Control In SPFx

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,
 
Output 
 
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:
  1. md directory-name  
Move to the above-created directory using:
  1. cd directory-name  
Now execute the below command to create an SPFx solution:
  1. yo @microsoft/sharepoint  
It will ask some questions, as shown below,
 
Project Setup 
 
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:
  1. code .  
Now we will install pnpjs and pnp-spfx-controls-react as shown below:
  1. npm install @pnp/sp --save    
  2. npm install @pnp/spfx-controls-react --save --save-exact  
Now go to the src > webparts > webpart > components > I{webpartname}Props.ts file,
  1. import { WebPartContext } from "@microsoft/sp-webpart-base";  
  2.   
  3. export interface IPnpReactAccordionProps {  
  4.   description: string;  
  5.   listName: string;  
  6.   context: WebPartContext;  
  7. }  
Create a file I{webpartname}State.ts inside src > webparts > webpart > components and create state interface as below,
  1. interface IListItem {  
  2.     Id?: string;  
  3.     Title: string;  
  4.     Description: string  
  5. }  
  6.   
  7. export interface IPnpReactAccordionState {  
  8.     listItems: IListItem[];  
  9.     errorMessage: string;  
  10. }  
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. 
  1. import { WebPartContext } from "@microsoft/sp-webpart-base";  
  2. import { sp } from '@pnp/sp/presets/all';  
  3.   
  4. export class SPService {  
  5.     constructor(private context: WebPartContext) {  
  6.         sp.setup({  
  7.             spfxContext: this.context  
  8.         });  
  9.     }  
  10.   
  11.     public async getListItems(listName: string) {  
  12.         try {  
  13.             let listItems: any[] = await sp.web.lists.getByTitle(listName)  
  14.                 .items  
  15.                 .select("Id,Title,Description")  
  16.                 .get();  
  17.             return listItems;  
  18.         } catch (err) {  
  19.             Promise.reject(err);  
  20.         }  
  21.     }  
  22. }  
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,
  1. import * as React from 'react';  
  2. import * as ReactDom from 'react-dom';  
  3. import { Version } from '@microsoft/sp-core-library';  
  4. import {  
  5.   IPropertyPaneConfiguration,  
  6.   PropertyPaneTextField  
  7. } from '@microsoft/sp-property-pane';  
  8. import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';  
  9.   
  10. import * as strings from 'PnpReactAccordionWebPartStrings';  
  11. import PnpReactAccordion from './components/PnpReactAccordion';  
  12. import { IPnpReactAccordionProps } from './components/IPnpReactAccordionProps';  
  13.   
  14. export interface IPnpReactAccordionWebPartProps {  
  15.   description: string;  
  16.   listName: string;  
  17. }  
  18.   
  19. export default class PnpReactAccordionWebPart extends BaseClientSideWebPart<IPnpReactAccordionWebPartProps> {  
  20.   
  21.   public render(): void {  
  22.     const element: React.ReactElement<IPnpReactAccordionProps> = React.createElement(  
  23.       PnpReactAccordion,  
  24.       {  
  25.         description: this.properties.description,  
  26.         listName: this.properties.listName,  
  27.         context: this.context  
  28.       }  
  29.     );  
  30.   
  31.     ReactDom.render(element, this.domElement);  
  32.   }  
  33.   
  34.   protected onDispose(): void {  
  35.     ReactDom.unmountComponentAtNode(this.domElement);  
  36.   }  
  37.   
  38.   protected get dataVersion(): Version {  
  39.     return Version.parse('1.0');  
  40.   }  
  41.   
  42.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  43.     return {  
  44.       pages: [  
  45.         {  
  46.           header: {  
  47.             description: strings.PropertyPaneDescription  
  48.           },  
  49.           groups: [  
  50.             {  
  51.               groupName: strings.BasicGroupName,  
  52.               groupFields: [  
  53.                 PropertyPaneTextField('description', {  
  54.                   label: strings.DescriptionFieldLabel  
  55.                 }),  
  56.                 PropertyPaneTextField('listName', {  
  57.                   label: strings.ListNameFieldLabel  
  58.                 })  
  59.               ]  
  60.             }  
  61.           ]  
  62.         }  
  63.       ]  
  64.     };  
  65.   }  
  66. }  
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, 
  1. import * as React from 'react';  
  2. import styles from './PnpReactAccordion.module.scss';  
  3. import { IPnpReactAccordionProps } from './IPnpReactAccordionProps';  
  4. import { IPnpReactAccordionState } from './IPnpReactAccordionState';  
  5. import { escape } from '@microsoft/sp-lodash-subset';  
  6. import { SPService } from '../../../Service/SPService';  
  7. import { Accordion } from "@pnp/spfx-controls-react/lib/Accordion";  
  8.   
  9. export default class PnpReactAccordion extends React.Component<IPnpReactAccordionProps, IPnpReactAccordionState> {  
  10.   
  11.   private _services: SPService = null;  
  12.   constructor(props: IPnpReactAccordionProps) {  
  13.     super(props);  
  14.     this.state = {  
  15.       listItems: [],  
  16.       errorMessage: ''  
  17.     }  
  18.     /** Bind service using current context */  
  19.     this._services = new SPService(this.props.context);  
  20.   }  
  21.   
  22.   public componentDidMount() {  
  23.     this.getListItems();  
  24.   }  
  25.   
  26.   /** Get items of selected list and set values in state */  
  27.   private async getListItems() {  
  28.     if (this.props.listName) {  
  29.       let items = await this._services.getListItems(this.props.listName);  
  30.       this.setState({ listItems: items });  
  31.     }  
  32.     else {  
  33.       this.setState({ errorMessage: 'Please enter the list name in property pane configuration.' });  
  34.     }  
  35.   }  
  36.   
  37.   public render(): React.ReactElement<IPnpReactAccordionProps> {  
  38.     return (  
  39.       <div className={styles.pnpReactAccordion}>  
  40.         {  
  41.           //Map list items and render in accordion  
  42.           (this.state.listItems && this.state.listItems.length) ? this.state.listItems.map((item, index) => (  
  43.             <Accordion title={item.Title} defaultCollapsed={true} className={"itemCell"} key={index}>  
  44.               <div className={"itemContent"}>  
  45.                 <div className={"itemResponse"} dangerouslySetInnerHTML={{ __html: item.Description }}></div>  
  46.               </div>  
  47.             </Accordion>  
  48.           )) : <p>{this.state.errorMessage}</p>  
  49.         }  
  50.       </div>  
  51.     );  
  52.   }  
  53. }  
Now serve the application using the below command,
  1. gulp serve  
Now test the webpart in SharePoint-SiteURL + /_layouts/15/workbench.aspx.
 
Output
 
PnP React Accordion 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!!