SharePoint Framework (SPFx) based web parts support integration with various JavaScript frameworks and libraries. We can include the npm package in our solution to get started with the various functionalities offered by that npm package.
In this article, we will explore how we can use Adaptive Cards with SharePoint Framework client web parts.
Adaptive Cards are a new way for the developers to exchange card content in a common and consistent way. Adaptive cards are a great fit for a Bot, however, they can be effectively used with SPFx to render the content. Read more about Adaptive Cards at https://adaptivecards.io/
Open the command prompt. Create a directory for SPFx solution.
- md react-adaptive-cards-image-gallery
Navigate to the above-created directory.
- cd react-adaptive-cards-image-gallery
Run Yeoman SharePoint Generator to create the solution.
The Yeoman generator will present you with the wizard by asking questions about the solution to be created.
Solution Name: Hit Enter to have a default name (react-adaptive-cards-image-gallery in this case) or type in any other name for your solution.
Selected choice: Hit Enter
Target for component: Here, we can select the target environment where we are planning to deploy the client webpart, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice: SharePoint Online only (latest)
Place of files: We may choose to use the same folder or create a subfolder for our solution.
Selected choice: Same folder
Deployment option: Selecting Y will allow the app to deployed instantly to all sites and to be accessible everywhere.
Selected choice: N (install on each site explicitly)
Type of client-side component to create: We can choose to create a client-side webpart or an extension. Choose the webpart option.
Selected choice: WebPart
Web part name: Hit Enter to select the default name or type in any other name.
Selected choice: AdaptiveCardsImageGallery
Web part description: Hit Enter to select the default description or type in any other value.
Selected choice: Image Gallery implemented with Adaptive Cards
Framework to use: Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice: React
Now, the Yeoman generator will perform scaffolding process to generate the solution. The scaffolding process will take a significant amount of time. Once the scaffolding process is completed, lock-down the version of the project dependencies by running the below command.
In the command prompt, type the below command to open the solution in a code editor of your choice.
NPM Packages
adaptivecards (https://www.npmjs.com/package/adaptivecards)
On the command prompt, run the below command to include the npm package.
- npm install adaptivecards --save
SP PnP JS
On the command prompt, run the below command to install sp-pnp-js.
- npm install sp-pnp-js --save
SharePoint Information Architecture
A SharePoint list (named "Adaptive Card Images") is provisioned to store the image information. The schema of the list is shown below.
- The "Image Link" column stores the URL of the image to be displayed in an adaptive card.
- The "Navigation URL" column represents the URL to navigate by clicking on an image in the adaptive card.
- The "Sort Order" column represents the order in which these images will be displayed in the adaptive card.
Define State
Add file IAdaptiveCardsImageGalleryState.ts under “\src\webparts\adaptiveCardsImageGallery\components\” folder.
- export interface IAdaptiveCardsImageGalleryState {
- galleryItems: any[];
- isLoading: boolean;
- showErrorMessage: boolean;
- }
Define Properties
Update IAdaptiveCardsImageGalleryProps.ts under “\src\webparts\adaptiveCardsImageGallery\components\” folder as below.
- import { ServiceScope } from '@microsoft/sp-core-library';
-
- export interface IAdaptiveCardsImageGalleryProps {
- serviceScope: ServiceScope;
- imageGalleryName: string;
- imagesToDisplay: number;
- }
Define Service
Define a service to retrieve the information from SharePoint list.
- import { ServiceKey, ServiceScope } from '@microsoft/sp-core-library';
- import { PageContext } from '@microsoft/sp-page-context';
- import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
- import * as pnp from "sp-pnp-js";
-
- export interface IImageGalleryService {
- getGalleryImages: (listName: string, rowLimit: number) => Promise<any[]>;
- }
-
- export class ImageGalleryService implements IImageGalleryService {
- public static readonly serviceKey: ServiceKey<IImageGalleryService> = ServiceKey.create<IImageGalleryService>('ImageGallery:ImageGalleryService', ImageGalleryService);
- private _pageContext: PageContext;
-
- constructor(serviceScope: ServiceScope) {
- serviceScope.whenFinished(() => {
- this._pageContext = serviceScope.consume(PageContext.serviceKey);
- });
- }
-
- public getGalleryImages(listName: string, rowLimit: number): Promise<any[]> {
- const xml = `<View>
- <ViewFields>
- <FieldRef Name='ID' />
- <FieldRef Name='Title' />
- <FieldRef Name='ImageLink' />
- <FieldRef Name='NavigationURL' />
- </ViewFields>
- <Query>
- <OrderBy>
- <FieldRef Name='SortOrder' />
- </OrderBy>
- </Query>
- <RowLimit>` + rowLimit + `</RowLimit>
- </View>`;
-
- const q: any = {
- ViewXml: xml,
- };
-
- return this._ensureList(listName).then((list) => {
- if (list) {
- return pnp.sp.web.lists.getByTitle(listName).getItemsByCAMLQuery(q).then((items: any[]) => {
- return Promise.resolve(items);
- });
- }
- });
- }
-
- private _ensureList(listName: string): Promise<pnp.List> {
- if (listName) {
- return pnp.sp.web.lists.ensure(listName).then((listEnsureResult) => Promise.resolve(listEnsureResult.list));
- }
- }
- }
Code the WebPart
Open the main webpart AdaptiveCardsImageGallery.tsx under “\src\webparts\adaptiveCardsImageGallery\components\” and add the below imports.
- import * as React from 'react';
- import styles from './AdaptiveCardsImageGallery.module.scss';
- import { IAdaptiveCardsImageGalleryProps } from './IAdaptiveCardsImageGalleryProps';
- import { IAdaptiveCardsImageGalleryState } from './IAdaptiveCardsImageGalleryState';
- import { escape } from '@microsoft/sp-lodash-subset';
-
- import * as AdaptiveCards from "adaptivecards";
- import { ImageGalleryService, IImageGalleryService } from '../services/ImageGalleryService';
- import { ServiceScope, Environment, EnvironmentType } from '@microsoft/sp-core-library';
- import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner';
Define render method.
- public render(): React.ReactElement<IAdaptiveCardsImageGalleryProps> {
- return (
- <div className={styles.adaptiveCardsImageGallery}>
- <div className={styles.container}>
- {this.state.isLoading && <Spinner className={styles.spinner} size={SpinnerSize.large} />}
- {!this.state.isLoading && <div ref={(n) => { n && n.appendChild(this.renderedCard) }} />}
- </div>
- </div>
- );
- }
In the constructor, create an AdaptiveCard instance as below.
-
- var adaptiveCard = new AdaptiveCards.AdaptiveCard();
-
-
-
- adaptiveCard.hostConfig = new AdaptiveCards.HostConfig({
- fontFamily: "Segoe UI, Helvetica Neue, sans-serif"
- });
-
-
-
- adaptiveCard.onExecuteAction = function(action) {
- window.location.href = action.iconUrl;
- };
-
-
- adaptiveCard.parse(this.card);
-
-
- this.renderedCard = adaptiveCard.render();
Define the card as below.
- this.card = {
- "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
- "type": "AdaptiveCard",
- "version": "1.0",
- "body": [
- {
- "type": "TextBlock",
- "text": "Adaptive Image Gallery",
- "size": "medium"
- },
- {
- "type": "ImageSet",
- "imageSize": "medium",
- "images": this.imagesJSON
- }
- ]
- };
Get the data from the service as below.
- let serviceScope: ServiceScope;
- serviceScope = this.props.serviceScope;
-
-
- if (Environment.type == EnvironmentType.SharePoint || Environment.type == EnvironmentType.ClassicSharePoint) {
-
- this.ImageGalleryServiceInstance = serviceScope.consume(ImageGalleryService.serviceKey);
- }
-
- this.ImageGalleryServiceInstance.getGalleryImages(this._galleryListName, this._noOfItems).then((galleryImages: any[]) => {
- galleryImages.forEach(adaptiveImage => {
- let image = {};
- image["type"] = "Image";
- image["url"] = adaptiveImage.ImageLink.Url;
-
-
- let imageAction = {};
- imageAction["title"] = adaptiveImage.NavigationURL.Description;
- imageAction["type"] = "Action.OpenUrl";
- imageAction["url"] = adaptiveImage.NavigationURL.Url;
- imageAction["iconUrl"] = adaptiveImage.NavigationURL.Url;
-
- image["selectAction"] = imageAction;
- this.imagesJSON.push(image);
- });
Run the SPFx WebPart
- On the command prompt, type “gulp serve”.
- Open SharePoint site.
- Navigate to /_layouts/15/workbench.aspx.
- Add the webpart to the page.
- Edit the web part and update the Image Gallery along with the number of images to display properties.
Summary