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,
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:
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:
Now we will install pnpjs as shown below:
- 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.
- import { WebPartContext } from "@microsoft/sp-webpart-base";
-
- export interface IPnpImageCarouselProps {
- listName: string;
- context: WebPartContext
- }
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,
- 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("Title,Description,Image")
- .expand().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 'PnpImageCarouselWebPartStrings';
- import PnpImageCarousel from './components/PnpImageCarousel';
- import { IPnpImageCarouselProps } from './components/IPnpImageCarouselProps';
-
- export interface IPnpImageCarouselWebPartProps {
- listName: string;
- }
-
- export default class PnpImageCarouselWebPart extends BaseClientSideWebPart<IPnpImageCarouselWebPartProps> {
-
- public render(): void {
- const element: React.ReactElement<IPnpImageCarouselProps> = React.createElement(
- PnpImageCarousel,
- {
- context: this.context,
- listName: this.properties.listName
- }
- );
-
- 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('listName', {
- label: strings.ListNameFieldLabel
- })
- ]
- }
- ]
- }
- ]
- };
- }
- }
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,
- import * as React from 'react';
- import styles from './PnpImageCarousel.module.scss';
- import { IPnpImageCarouselProps } from './IPnpImageCarouselProps';
- import { escape } from '@microsoft/sp-lodash-subset';
- import { SPService } from '../../../service/SPService'
- import { ImageFit } from 'office-ui-fabric-react';
- import { Carousel, CarouselButtonsLocation, CarouselButtonsDisplay, CarouselIndicatorShape } from "@pnp/spfx-controls-react/lib/Carousel";
-
- export interface IPnpImageCarouselState {
- listItems: any[];
- errorMessage: string;
- }
-
- export default class PnpImageCarousel extends React.Component<IPnpImageCarouselProps, IPnpImageCarouselState>{
-
- private SPService: SPService = null;
- constructor(props: IPnpImageCarouselProps) {
- super(props);
- this.SPService = new SPService(this.props.context);
- this.getCarouselItems = this.getCarouselItems.bind(this);
- this.state = {
- listItems: [],
- errorMessage: ''
- };
- }
-
- public async getCarouselItems() {
- if (this.props.listName) {
- let carouselItems = await this.SPService.getListItems(this.props.listName);
- let carouselItemsMapping = carouselItems.map(e => ({
- imageSrc: JSON.parse(e.Image).serverRelativeUrl,
- title: e.Title,
- description: e.Description,
- showDetailsOnHover: true,
- url: JSON.parse(e.Image).serverRelativeUrl,
- imageFit: ImageFit.cover
- }));
- this.setState({ listItems: carouselItemsMapping });
- }
- else {
- this.setState({ errorMessage: "Please set proper list name in property pane configuration." })
- }
- }
-
- public componentDidMount() {
- this.getCarouselItems();
- }
-
- public render(): React.ReactElement<IPnpImageCarouselProps> {
- return (
- <div className={styles.pnpImageCarousel}>
- { this.state.listItems && this.state.listItems.length ?
- <Carousel
- buttonsLocation={CarouselButtonsLocation.center}
- buttonsDisplay={CarouselButtonsDisplay.buttonsOnly}
- contentContainerStyles={styles.carouselContent}
- isInfinite={false}
- indicatorShape={CarouselIndicatorShape.circle}
- pauseOnHover={true}
- element={this.state.listItems}
- containerButtonsStyles={styles.carouselButtonsContainer}
- />
- : <p>{this.state.errorMessage}</p>
- }
- </div>
- );
- }
- }
Move to the {webpartname}.module.scss file. Here we will add some CSS related to the carousel as below,
- @import '~office-ui-fabric-react/dist/sass/References.scss';
-
- .pnpImageCarousel {
- .carouselContent {
- height: 500px !important;
- }
-
- div[class^="details"] {
- top: 80% !important;
-
- span {
- font-size: 15px !important;
- }
-
- span[class^="title"] {
- font-size: 20px !important;
- }
- }
-
- .carouselButtonsContainer button {
- min-width: 32px !important;
- }
- }
-
-
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 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!