How To Use Carousel Control Of PnP In SPFx Webpart?

Introduction

 
Carousel is a popular control used in many web applications. We can develop it manually in SPFx Webpart using bootstrap or using javascript & CSS. Writing these controls manually is cumbersome. We need to manage each event manually.
 
To use PnP controls in our application we will use @pnp/spfx-controls-react library. This library provides a set of reusable React controls that can be used in SharePoint Framework (SPFx) solutions. This library provides controls for building web parts and extensions. 
 
For more details, refer to this.
 
  

Scenario

 
In this example, we will create a list called "Carousel" and in the list, we will create a Description field (it will be multiple lines of text), Image field (It will be hyperlink/picture).
 
We will use PnPJs to get list items and then will render them in the carousel form.
 
At the end, our output will be like this,
 
Output 
 
 

Implementation

 
Create a SharePoint list and in this list create fields like Title (Single line of text), Description (Multiline of text), Image (Hyperlink/Picture).
 
After the creation of the list, we will start to implement spfx webpart.
  • Open a command prompt
  • Move to the path where you want to create a project
  • Create a project directory using:        
  1. md pnp-image-carousel  
Move to the above-created directory using:
  1. cd pnp-image-carousel    
Now execute the below command to create an SPFx solution:
  1. yo @microsoft/sharepoint  
It will ask some questions, as shown below,
 
Project Setup - PnP Image Carousel 
 
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 as shown below:
  1. npm install @pnp/sp --save    
Now go to the src > webparts > webpart > components > I{webpartname}Props.ts file,
 
Here we will pass the list name from the property pane configuration.
  1. import { WebPartContext } from "@microsoft/sp-webpart-base";  
  2.   
  3. export interface IPnpImageCarouselProps {  
  4.   listName: string;  
  5.   context: WebPartContext  
  6. }  
Create a Service folder inside the src folder 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,
  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("Title,Description,Image")  
  16.                 .expand().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 'PnpImageCarouselWebPartStrings';  
  11. import PnpImageCarousel from './components/PnpImageCarousel';  
  12. import { IPnpImageCarouselProps } from './components/IPnpImageCarouselProps';  
  13.   
  14. export interface IPnpImageCarouselWebPartProps {  
  15.   listName: string;  
  16. }  
  17.   
  18. export default class PnpImageCarouselWebPart extends BaseClientSideWebPart<IPnpImageCarouselWebPartProps> {  
  19.   
  20.   public render(): void {  
  21.     const element: React.ReactElement<IPnpImageCarouselProps> = React.createElement(  
  22.       PnpImageCarousel,  
  23.       {  
  24.         context: this.context,  
  25.         listName: this.properties.listName         
  26.       }  
  27.     );  
  28.   
  29.     ReactDom.render(element, this.domElement);  
  30.   }  
  31.   
  32.   protected onDispose(): void {  
  33.     ReactDom.unmountComponentAtNode(this.domElement);  
  34.   }  
  35.   
  36.   protected get dataVersion(): Version {  
  37.     return Version.parse('1.0');  
  38.   }  
  39.   
  40.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  41.     return {  
  42.       pages: [  
  43.         {  
  44.           header: {  
  45.             description: strings.PropertyPaneDescription  
  46.           },  
  47.           groups: [  
  48.             {  
  49.               groupName: strings.BasicGroupName,  
  50.               groupFields: [  
  51.                 PropertyPaneTextField('listName', {  
  52.                   label: strings.ListNameFieldLabel  
  53.                 })  
  54.               ]  
  55.             }  
  56.           ]  
  57.         }  
  58.       ]  
  59.     };  
  60.   }  
  61. }  
Move to the {webpartname}.tsx file.
 
Step 1
 
Create a state interface with listItems and errorMessage properties.
 
Step 2 
 
bind the service using current context and the call service for getting list items and set values in the state
 
Step 3 
 
Map state object in another object form as we require in the carousel,
  1. import * as React from 'react';  
  2. import styles from './PnpImageCarousel.module.scss';  
  3. import { IPnpImageCarouselProps } from './IPnpImageCarouselProps';  
  4. import { escape } from '@microsoft/sp-lodash-subset';  
  5. import { SPService } from '../../../service/SPService'  
  6. import { ImageFit } from 'office-ui-fabric-react';  
  7. import { Carousel, CarouselButtonsLocation, CarouselButtonsDisplay, CarouselIndicatorShape } from "@pnp/spfx-controls-react/lib/Carousel";  
  8.   
  9. export interface IPnpImageCarouselState {  
  10.   listItems: any[];  
  11.   errorMessage: string;  
  12. }  
  13.   
  14. export default class PnpImageCarousel extends React.Component<IPnpImageCarouselProps, IPnpImageCarouselState>{  
  15.   
  16.   private SPService: SPService = null;  
  17.   constructor(props: IPnpImageCarouselProps) {  
  18.     super(props);  
  19.     this.SPService = new SPService(this.props.context);  
  20.     this.getCarouselItems = this.getCarouselItems.bind(this);  
  21.     this.state = {  
  22.       listItems: [],  
  23.       errorMessage: ''  
  24.     };  
  25.   }  
  26.   
  27.   public async getCarouselItems() {  
  28.     if (this.props.listName) {  
  29.       let carouselItems = await this.SPService.getListItems(this.props.listName);  
  30.       let carouselItemsMapping = carouselItems.map(e => ({  
  31.         imageSrc: JSON.parse(e.Image).serverRelativeUrl,  
  32.         title: e.Title,  
  33.         description: e.Description,  
  34.         showDetailsOnHover: true,  
  35.         url: JSON.parse(e.Image).serverRelativeUrl,  
  36.         imageFit: ImageFit.cover  
  37.       }));  
  38.       this.setState({ listItems: carouselItemsMapping });  
  39.     }  
  40.     else {  
  41.       this.setState({ errorMessage: "Please set proper list name in property pane configuration." })  
  42.     }  
  43.   }  
  44.   
  45.   public componentDidMount() {  
  46.     this.getCarouselItems();  
  47.   }  
  48.   
  49.   public render(): React.ReactElement<IPnpImageCarouselProps> {  
  50.     return (  
  51.       <div className={styles.pnpImageCarousel}>  
  52.         { this.state.listItems && this.state.listItems.length ?  
  53.           <Carousel  
  54.             buttonsLocation={CarouselButtonsLocation.center}  
  55.             buttonsDisplay={CarouselButtonsDisplay.buttonsOnly}  
  56.             contentContainerStyles={styles.carouselContent}  
  57.             isInfinite={false}  
  58.             indicatorShape={CarouselIndicatorShape.circle}  
  59.             pauseOnHover={true}  
  60.             element={this.state.listItems}  
  61.             containerButtonsStyles={styles.carouselButtonsContainer}  
  62.           />  
  63.           : <p>{this.state.errorMessage}</p>  
  64.         }  
  65.       </div>  
  66.     );  
  67.   }  
  68. }     
Move to the {webpartname}.module.scss file. Here we will add some CSS related to the carousel as below,
  1. @import '~office-ui-fabric-react/dist/sass/References.scss';  
  2.   
  3. .pnpImageCarousel {  
  4.     .carouselContent {  
  5.       height500px !important;  
  6.     }  
  7.   
  8.     div[class^="details"] {  
  9.       top: 80% !important;  
  10.   
  11.       span {  
  12.         font-size15px !important;  
  13.       }  
  14.   
  15.       span[class^="title"] {  
  16.         font-size20px !important;  
  17.       }  
  18.     }  
  19.       
  20.     .carouselButtonsContainer button {  
  21.       min-width32px !important;  
  22.     }  
  23.   }  
  24.   
  25.     
Now serve the application using the below command,
  1. gulp serve  
Now test the webpart in SharePoint-SiteURL + /_layouts/15/workbench.aspx.
 
Output
 
Output 
Find the full source code here
 

Summary 

 
In this article, we have seen the step-by-step implementation of Carousel Control Of PnP in SPFx Web part.
 
I hope this helps; if this helps you then share it with others.
 
Sharing is caring!