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:
Move to the above-created directory using:
Now execute the below command to create an SPFx solution:
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:
- 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;
- }
Create a file I{webpartname}State.ts inside
src > webparts > webpart > components and create state interface as below,
- 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: ''
- }
-
- this._services = new SPService(this.props.context);
- }
-
- public componentDidMount() {
- this.getListItems();
- }
-
-
- 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}>
- {
-
- (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,
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!!