Tag: SPFX

PnP Taxonomy Picker in the SharePoint Framework (SPFx) web part

This article provides steps to implement the PnP Taxonomy Picker in the SharePoint Framework (SPFx) web part, This Taxonomy Picker control allows you to select one or more Terms from a TermSet via its name or TermSet ID. You can also configure the control to select the child terms from a specific term in the TermSet by setting the AnchorId. In this article we using PnP Taxonomy Picker to set and get the value for SharePoint Managed Matadata field.

Create a new web part project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install @pnp/sp --save
npm install @pnp/spfx-controls-react --save --save-exact

Import the library into your application, update constructor, and access the root sp object in render for PnPjs libraries.

sp.setup({spfxContext: this.props.spcontect});

Configure the custom properties

Create a new source code file under the src\webparts\<Webpart name>\components\ folder of the solution. Create the new file I<web part name>State.ts and use it to create a TypeScript Interface

import {  IPickerTerms } from "@pnp/spfx-controls-react/lib/TaxonomyPicker";
export interface ISpfxPnpTaxonomypickerState {
  tags: IPickerTerms;
}

In addition, you need to update the render method of the client-side web part to create a properly configured instance of the React component for rendering. The following code shows the updated method definition.

  public render(): void {
    const element: React.ReactElement<ISpfxPnpTaxonomypickerProps> = React.createElement(
      SpfxPnpTaxonomypicker,
      {
        description: this.properties.description,
        context:this.context
      }
    );
    ReactDom.render(element, this.domElement);
  }

Update the tsx file under the components. First, add some import statements to import the types you defined earlier. Notice the import for I<web part name>Props and I<web part name>State. There are also some imports for the PnP components used to render the UI of the PnP React component and pnp sp imports.

import * as React from 'react';
import styles from './SpfxPnpTaxonomypicker.module.scss';
import { ISpfxPnpTaxonomypickerProps } from './ISpfxPnpTaxonomypickerProps';
import { ISpfxPnpTaxonomypickerState } from './ISpfxPnpTaxonomypickerState';
import { TaxonomyPicker, IPickerTerms } from "@pnp/spfx-controls-react/lib/TaxonomyPicker";
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import "@pnp/sp/fields";

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxPnpTaxonomypickerProps> {
    return (
      <div className={styles.spfxPnpTaxonomypicker}>
        <TaxonomyPicker allowMultipleSelections={true}
          initialValues={this.state.tags}
          termsetNameOrID="Department"
          panelTitle="Select Departments"
          label="Departments Picker"
          context={this.props.context}
          onChange={this.onMultySelectTaxPickerChange}
          isTermSetSelectable={false} />
      </div>
    );
  }

Update the React component type declaration and add a constructor, as shown in the following example.

export default class SpfxPnpTaxonomypicker extends React.Component<ISpfxPnpTaxonomypickerProps, ISpfxPnpTaxonomypickerState> {
  constructor(props: ISpfxPnpTaxonomypickerProps) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
    this.state = ({ tags: [] });
    this._gettags();
  }

place the below code inside the react component code, these functions using PnPjs to get and set values in to the Managed Metadata Field

  private async _gettags() {
    const item: any = await sp.web.lists.getByTitle("GroupTags").items.getById(1).get();
    let selectedtags: any = [];
    item.Tags.forEach(function (v: any[], i) {
      selectedtags.push({ key: v["TermGuid"], name: v["Label"] })
    });
    console.log(item);
    this.setState({
      tags: selectedtags
    });
  }

  //Use this function if your control's select type is Multy
  private async onMultySelectTaxPickerChange(terms: IPickerTerms) {
    let list = sp.web.lists.getByTitle("GroupTags");
    const field = await list.fields.getByTitle(`Tags_0`).get();
    let termsString: string = '';
    terms.forEach(function (v, i) {
      termsString += `-1;#${v.name}|${v.key};#`;
    })
    const data = {};
    data[field.InternalName] = termsString;
    const i = await list.items.getById(1).update(data);
  }

  //Use this function if your control's select type is Single
  private async onSingleSelectTaxPickerChange(terms: IPickerTerms) {
    const data = {};
    data['Tags'] = {
      "__metadata": { "type": "SP.Taxonomy.TaxonomyFieldValue" },
      "Label": terms[0].name,
      'TermGuid': terms[0].key,
      'WssId': '-1'
    };
    return await sp.web.lists.getByTitle("GroupTags").items.getById(1).update(data);
  }

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle --ship
gulp package-solution --ship

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

QR Code Generator in the SharePoint Framework (SPFx) web part

This article provides steps to implement the QR Code Generator in the SharePoint Framework (SPFx) web part, generally, QR Code Generator is a simple and convenient tool that help you create QR Code image displayed on the screen. Several content types are supported, include Text, Url, Email, Phone number, Contact, Geolocation and SMS.

Create a new web part project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install --save qrcode

In the react component properties interface file, replace below properties  

export interface ISpfxQrcodeProps {
  qrcontent: string;
  qrcodedata: string;
}

In the client-side web part class file, import the QRCode and the modify the client-side web part properties, property pane configuration and render functions are modified according to get and set QR code values, please refer below code.  

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 'SpfxQrcodeWebPartStrings';
import SpfxQrcode from './components/SpfxQrcode';
import { ISpfxQrcodeProps } from './components/ISpfxQrcodeProps';
import QRCode from 'qrcode'

export interface ISpfxQrcodeWebPartProps {
  qrcontent: string;
}

export default class SpfxQrcodeWebPart extends BaseClientSideWebPart<ISpfxQrcodeWebPartProps> {

  public render(): void {
    QRCode.toDataURL(this.properties.qrcontent)
      .then(url => {
        const element: React.ReactElement<ISpfxQrcodeProps> = React.createElement(
          SpfxQrcode,
          {
            qrcontent: this.properties.qrcontent,
            qrcodedata: url
          }
        );
        ReactDom.render(element, this.domElement);
      })
      .catch(err => {
        console.error(err)
      })
  }

  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('qrcontent', {
                  label: 'Code content'
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

In the react component just replace the default render function to blow render function we just add the image to display the code  

import * as React from 'react';
import styles from './SpfxQrcode.module.scss';
import { ISpfxQrcodeProps } from './ISpfxQrcodeProps';

export default class SpfxQrcode extends React.Component<ISpfxQrcodeProps, {}> {
  public render(): React.ReactElement<ISpfxQrcodeProps> {
    return (
      <div className={styles.spfxQrcode}>
        <img className={styles.img} src={this.props.qrcodedata} alt={this.props.qrcontent} />
        <small>{this.props.qrcontent}</small>
      </div>
    );
  }
}

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle --ship
gulp package-solution --ship

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

For your reference, this complete project added in to the GitHub

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

Document Card Carousel in The SharePoint Framework (SPFx) web part

This article provides steps to implement the Document Card Carousel in The SharePoint Framework (SPFx) web part, generally, A DocumentCard is a card representation of a file. This is usually richer than just seeing the file in a grid view, as the card can contain additional metadata or actions. In this article we using PnP Carousel control to roll the DocumentCard, files are retrieved from the SharePoint Document Library 

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install @pnp/sp --save
npm install @pnp/spfx-controls-react --save --save-exact

Import the library into your application, update constructor, and access the root sp object in render for PnPjs libraries.

sp.setup({spfxContext: this.props.spcontect});

Configure the custom properties

Create a new source code file under the src\webparts\<Webpart name>\components\ folder of the solution. Create the new file I<web part name>State.ts and use it to create a TypeScript Interface

export interface ISpfxFluentuiDocumentcardState {
  carouselElements: JSX.Element[];
}

In addition, you need to update the render method of the client-side web part to create a properly configured instance of the React component for rendering. The following code shows the updated method definition.

  public render(): void {
    const element: React.ReactElement<ISpfxFluentuiDocumentcardProps> = React.createElement(
      SpfxFluentuiDocumentcard,
      {
        description: this.properties.description,
        context: this.context
      }
    );
    ReactDom.render(element, this.domElement);
  }

Update the tsx file under the components. First, add some import statements to import the types you defined earlier. Notice the import for I<web part name>Props and I<web part name>State. There are also some imports for the PnP components used to render the UI of the PnP React component and pnp sp imports.

import * as React from 'react';
import styles from './SpfxFluentuiDocumentcard.module.scss';
import { ISpfxFluentuiDocumentcardProps } from './ISpfxFluentuiDocumentcardProps';
import { ISpfxFluentuiDocumentcardState } from './ISpfxFluentuiDocumentcardState';
import { Carousel, CarouselButtonsLocation, CarouselButtonsDisplay } from "@pnp/spfx-controls-react/lib/Carousel";
import { autobind } from 'office-ui-fabric-react/lib/Utilities';

import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/files";
import "@pnp/sp/folders";

import {
  DocumentCard,
  DocumentCardActivity,
  DocumentCardPreview,
  DocumentCardDetails,
  DocumentCardTitle,
  IDocumentCardPreviewProps,
  DocumentCardLocation,
  DocumentCardType
} from 'office-ui-fabric-react/lib/DocumentCard';
import { ImageFit } from 'office-ui-fabric-react/lib/Image';
import { ISize } from 'office-ui-fabric-react/lib/Utilities';

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxFluentuiDocumentcardProps> {
    return (
      <div className={styles.spfxFluentuiDocumentcard}>
        <Carousel
          buttonsLocation={CarouselButtonsLocation.top}
          buttonsDisplay={CarouselButtonsDisplay.block}
          isInfinite={true}
          element={this.state.carouselElements}
          onMoveNextClicked={(index: number) => { console.log(`Next button clicked: ${index}`); }}
          onMovePrevClicked={(index: number) => { console.log(`Prev button clicked: ${index}`); }}
        />
      </div>
    );
  }

Update the React component type declaration and add a constructor, as shown in the following example.

export default class SpfxFluentuiDocumentcard extends React.Component<ISpfxFluentuiDocumentcardProps, ISpfxFluentuiDocumentcardState> {
  constructor(props: ISpfxFluentuiDocumentcardProps, state: ISpfxFluentuiDocumentcardState) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
    this.state = {
      carouselElements: []
    };

    this._getFiles();
  }

place the below code inside the react component code, these functions using PnPjs to get files from the SharePoint document library and building the document card elements

  @autobind
  private async _getFiles() {
    let cardsdata: any[] = [];
    const items: any[] = await sp.web.getFolderByServerRelativeUrl("/sites/TheLanding/Books").files.select().expand("ListItemAllFields,Author").get();
    let siteurl = this.props.context.pageContext.web.absoluteUrl;
    let siterooturl = this.props.context.pageContext.web.absoluteUrl.replace(this.props.context.pageContext.web._serverRelativeUrl, "");
    // const items: any[] = await sp.web.lists.getByTitle("Documents").items.get();
    items.forEach(function (v, i) {
      let url = siterooturl + v.ServerRelativeUrl;
      console.log(v);
      cardsdata.push({
        thumbnail: siteurl + '/_layouts/15/getpreview.ashx?resolution=1&path=' + encodeURIComponent(url),
        title: v.Name,
        name: v.Author.Title,
        profileImageSrc: siteurl + "/_layouts/15/userphoto.aspx?AccountName=" + v.Author.LoginName + "&Size=L",
        location: "SharePoint",
        activity: v.TimeLastModified,
        url: url
      })
    });
    let cardsElements: JSX.Element[] = [];

    cardsdata.forEach(item => {
      const previewProps: IDocumentCardPreviewProps = {
        previewImages: [
          {
            previewImageSrc: item.thumbnail,
            imageFit: ImageFit.cover,
            height: 130
          }
        ]
      };
      cardsElements.push(<div>
        <DocumentCard
          type={DocumentCardType.normal}
          onClick={(ev: React.SyntheticEvent<HTMLElement>) => alert("You clicked on a grid item")}>
          <DocumentCardPreview {...previewProps} />
          <DocumentCardLocation location={item.location} />
          <DocumentCardDetails>
            <DocumentCardTitle
              title={item.title}
              shouldTruncate={true} />
            <DocumentCardActivity
              activity={item.activity}
              people={[{ name: item.name, profileImageSrc: item.profileImageSrc }]} />
          </DocumentCardDetails>
        </DocumentCard>
      </div>);
    });
    this.setState({ carouselElements: cardsElements });
  }

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle --ship
gulp package-solution --ship

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

For your reference, this complete project added in the GitHub

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

Modern Page Provisioning in the SharePoint Framework (SPFx)

This article provides steps to implement the mordern page provisioning using PnPjs in the SharePoint Framework (SPFx), generally PnPjs clientside pages module allows you to created, edit, and delete modern SharePoint pages. There are methods to update the page settings and add/remove client-side webparts.

Create a new web part project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install @pnp/sp --save

Import the library into your application, update constructor, and access the root sp object in render for PnPjs libraries.

sp.setup({spfxContext: this.props.spcontect});

Configure the custom properties

Create a new source code file under the src\webparts\<Webpart name>\components\ folder of the solution. Create the new file I<web part name>State.ts and use it to create a TypeScript Interface

export interface ISpfxPnpPageprovisioningState {
  title: string;
  name:string;
}

In addition, you need to update the render method of the client-side web part to create a properly configured instance of the React component for rendering. The following code shows the updated method definition.

  public render(): void {
    const element: React.ReactElement<ISpfxPnpPageprovisioningProps> = React.createElement(
      SpfxPnpPageprovisioning,
      {
        description: this.properties.description,
        context:this.context
      }
    );
    ReactDom.render(element, this.domElement);
  }

Update the tsx file located under the components. First, add some import statements to import the types you defined earlier. Notice the import for I<web part name>Props and I<web part name>State. There are also some imports pnp sp imports.

import * as React from 'react';
import styles from './SpfxPnpPageprovisioning.module.scss';
import { ISpfxPnpPageprovisioningProps } from './ISpfxPnpPageprovisioningProps';
import { ISpfxPnpPageprovisioningState } from './ISpfxPnpPageprovisioningState';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/clientside-pages/web";
import { PrimaryButton, TextField } from 'office-ui-fabric-react';
import { ClientsideText, ClientsideWebpart } from "@pnp/sp/clientside-pages";
import "@pnp/sp/comments/clientside-page";

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxPnpPageprovisioningProps> {
    return (
      <div className={styles.spfxPnpPageprovisioning}>
        <TextField label="Page Name" onChanged={(val) => { this.setState({ name: val }) }} />
        <TextField label="Page Title" onChanged={(val) => { this.setState({ title: val }) }} />
        <br />
        <PrimaryButton text="Create Page" onClick={this._CreatePage} />
      </div>
    );
  }

Update the React component type declaration and add a constructor, as shown in the following example.

export default class SpfxPnpPageprovisioning extends React.Component<ISpfxPnpPageprovisioningProps, ISpfxPnpPageprovisioningState> {
  constructor(props: ISpfxPnpPageprovisioningProps) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
    this.state = {
      title: '',
      name: ''
    }
  }

place the below code inside the react component code, these function using PnPjs to create modern page in the Site Pages library

@autobind
  private async _CreatePage() {
    //Page layout type are "Article" | "Home"
    const page = await sp.web.addClientsidePage(this.state.name, this.state.title, "Article");
    let section = page.addSection()
    //Column size factor. Max value is 12 (= one column), other options are 8,6,4 or 0
    let column1 = section.addColumn(8);
    let column2 = section.addColumn(4);

    column1.addControl(new ClientsideText("This is text added into column 1"))
    column2.addControl(new ClientsideText("This is text added into column 2"))

    const partDefs = await sp.web.getClientsideWebParts();
    const partDef = partDefs.filter(c => c.Id === "490d7c76-1824-45b2-9de3-676421c997fa");
    const part = ClientsideWebpart.fromComponentDef(partDef[0]);
    column1.addControl(part);
    await page.save();
    // //Header
    // page.topicHeader = "My cool header!";
    // page.headerTextAlignment = "Center";

    // //You can manage to show and hide the published date
    // page.showPublishDate = true;

    // //can hide/show the comments
    // await page.enableComments();
    // //Banner image can change like this
    // page.bannerImageUrl = "/server/relative/path/to/image.png";
  }

Webpart name and id for your reference

ContentRollupWebPart ------- daf0b71c-6de8-4ef7-b511-faae7c388708
BingMapsWebPart ------- e377ea37-9047-43b9-8cdb-a761be2f8e09
ButtonWebPart ------- 0f087d7f-520e-42b7-89c0-496aaf979d58
CallToActionWebPart ------- df8e44e7-edd5-46d5-90da-aca1539313b8
CodeSnippetWebPart ------- 7b317bca-c919-4982-af2f-8399173e5a1e
ConnectorWebPart ------- 893a257e-9c92-49bc-8a36-2f6bb058da34
ContentEmbedWebPart ------- 490d7c76-1824-45b2-9de3-676421c997fa
CountdownWebPart ------- 62cac389-787f-495d-beca-e11786162ef4
CustomMessage ------- 71c19a43-d08c-4178-8218-4df8554c0b0e
DividerWebPart ------- 2161a1c6-db61-4731-b97c-3cdb303f7cbb
DocumentEmbedWebPart ------- b7dd04e1-19ce-4b24-9132-b60a1c2b910d
EventsWebPart ------- 20745d7d-8581-4a6c-bf26-68279bc123fc
FieldsWebPart ------- cf91cf5d-ac23-4a7a-9dbc-cd9ea2a4e859
FormsWebPart ------- b19b3b9e-8d13-4fec-a93c-401a091c0707
GroupCalendarWebPart ------- 6676088b-e28e-4a90-b9cb-d0d0303cd2eb
HeroWebPart ------- c4bd7b2f-7b6e-4599-8485-16504575f590
ImageWebPart ------- d1d91016-032f-456d-98a4-721247c305e8
ImageGalleryWebPart ------- af8be689-990e-492a-81f7-ba3e4cd3ed9c
KindlePreviewWebPart ------- 46698648-fcd5-41fc-9526-c7f7b2ace919
LinkPreviewWebPart ------- 6410b3b6-d440-4663-8744-378976dc041e
ListPropertiesWebPart ------- a8cd4347-f996-48c1-bcfb-75373fed2a27
ListWebPart ------- f92bf067-bc19-489e-a556-7fe95f508720
MarkdownWebPart ------- 1ef5ed11-ce7b-44be-bc5e-4abd55101d16
MyDocumentsWebPart ------- b519c4f1-5cf7-4586-a678-2f1c62cc175a
NewsWebPart ------- 8c88f208-6c77-4bdb-86a0-0c47b4316588
NewsfeedWebPart ------- 0ef418ba-5d19-4ade-9db0-b339873291d0
NewsLink ------- c1b5736d-84dd-4fdb-a7be-e7e9037bd3c3
NewsreelWebPart ------- a5df8fdf-b508-4b66-98a6-d83bc2597f63
PageTitle ------- cbe7b0a9-3504-44dd-a3a3-0e5cacd07788
PeopleWebPart ------- 7f718435-ee4d-431c-bdbf-9c4ff326f46e
PlannerWebPart ------- 39c4c1c2-63fa-41be-8cc2-f6c0b49b253d
PowerAppPlayerWebPart ------- 9d7e898c-f1bb-473a-9ace-8b415036578b
PowerBIReportEmbedWebPart ------- 58fcd18b-e1af-4b0a-b23b-422c2c52d5a2
QuickChartWebPart ------- 91a50c94-865f-4f5c-8b4e-e49659e69772
QuickLinksWebPart ------- c70391ea-0b10-4ee9-b2b4-006d3fcad0cd
SiteActivityWebPart ------- eb95c819-ab8f-4689-bd03-0c2d65d47b1f
SitesWebPart ------- 7cba020c-5ccb-42e8-b6fc-75b3149aba7b
SpacerWebPart ------- 8654b779-4886-46d4-8ffb-b5ed960ee986
DocLibWebPart ------- 6ee6fe3d-ed5f-4c42-b663-b1df52a8ae3b
FileViewerWebPart ------- 2a8b07f2-b38f-4df0-8e8b-2cd2a8b8d32b
ImageViewerWebPart ------- 5e945ea8-0e6c-4f52-b7c2-75ae618396e5
MRModelViewerWebPart ------- e19cef07-c1ad-42ea-a3d8-a536d6415476
People ------- 102f1fc1-3369-4372-8e44-f27dd11a9377
SpacesTestWebPart ------- b3a690f0-bed6-4ccb-a186-ed70412fc35b
Text2DWebPart ------- e30ff702-e1a4-4e02-8c11-3cce0139727a
MrImageThreeSixtyWebPart ------- 8bcd4369-10e6-46a9-b718-fa47db2864ca
MrVideoThreeSixtyWebPart ------- 4bdfb4be-6e39-4b1d-af8b-addbd3a582ff
VideoPlayerWebPart ------- 8902cf6d-22e5-4615-b036-57c613b8db6b
TwitterWebPart ------- f6fdf4f8-4a24-437b-a127-32e66a5dd9b4
EmbeddedVideoWebPart ------- 275c0095-a77e-4f6d-a2a0-6a7626911518
WeatherWebPart ------- 868ac3c3-cad7-4bd6-9a1c-14dc5cc8e823
WorldClockWebPart ------- 81b57906-cbed-4bb1-9823-2e3314f46f28
YammerFullFeedWebPart ------- cb3bfe97-a47f-47ca-bffb-bb9a5ff83d75
YammerEmbedWebPart ------- 31e9537e-f9dc-40a4-8834-0e3b7df418bc
YouTubeEmbedWebPart ------- 544dd15b-cf3c-441b-96da-004d5a8cea1d
tslib ------- 01c4df03-e775-48cb-aa14-171ee5199a15
SPTelemetry ------- 8217e442-8ed3-41fd-957d-b112e841286a
SPSuiteNav ------- f8a8ad94-4cf3-4a19-a76b-1cec9da00219
SPLoader ------- 1c6c9123-7aac-41f3-a376-3caea41ed83f
OfficeUIFabricReact ------- 02a01e42-69ab-403d-8a16-acd128661f8e
SPLodashSubset ------- 73e1dc6c-8441-42cc-ad47-4bd3659f8a3a
SPDataProviders ------- 1cea229f-b208-4202-8014-22503d92a019
sp-webpart-shared ------- 914330ee-2df2-4f6e-a858-30c23a812408
SPCoreLibrary ------- 7263c7d0-1d6a-45ec-8d85-d4d1d234171b
SPPageContext ------- 1c4541f7-5c31-41aa-9fa8-fbc9dc14c0a8
SPWebPartBase ------- 974a7777-0990-4136-8fa6-95d80114c2e0
FabricStyling ------- 17ce0976-e69a-4355-be84-89b69a74717d
SPComponentUtilities ------- 8494e7d7-6b99-47b2-a741-59873e42f16f
SPLoadThemedStyles ------- 229b8d08-79f3-438b-8c21-4613fc877abd
SPDeferredComponent ------- fa4155f6-2498-4a20-8406-5cb3b385b142
SPDiagnostics ------- 78359e4b-07c2-43c6-8d0b-d060b4d577e8
Decorators ------- f97266fb-ccb7-430e-9384-4124d05295d3
OdspUtilitiesBundle ------- cc2cc925-b5be-41bb-880a-f0f8030c6aff
SPComponentBase ------- 467dc675-7cc5-4709-8aac-78e3b71bd2f6
SPBingMap ------- ab22169a-a644-4b69-99a2-4295eb0f633c
RichImage ------- 4e1d8ea3-d90c-46fc-b4a1-367b9bc0046a
SPHttp ------- c07208f0-ea3b-4c1a-9965-ac1b825211a6
SPEmbedWebPartBase ------- 1de47009-ab52-4ff1-a8ed-f5876549bcac
SPHtmlEmbed ------- 3fbad3f4-a628-41b0-8694-2054c09edccd
SPPropertyPane ------- f9e737b7-f0df-4597-ba8c-3060f82380db
I18nUtilities ------- c83d5509-ccd5-4c67-919f-2440f237927a
FlexLayout ------- 0447e11d-bed9-4898-b600-8dbcd95e9cc2
SPCarouselLayout ------- 8ac0c53c-e8d0-4e3e-87d0-7449eb0d4027
SPA11y ------- 05ed6956-59ad-4aa6-9e4e-b832c96ae87b
SpListViewCommon ------- 5f18a9a1-d34e-4b05-a71f-e5e554d8649b
ListDocumentLayout ------- c6eb85d4-7fd2-4938-bfb8-5a899344ee86
GridLayout ------- 706e33c8-af37-4e7b-9d22-6e5694d92a6f
SPTopicShared ------- 49d290fb-a38e-4001-97d3-a2db486db2fa
SPSitePicker ------- 7ad20b0d-6a5d-43c3-a111-8c7f425b6bf2
sp-safehtml ------- 6d3c733c-8cb7-4871-bb22-b5b37c1d518d
BabylonJs ------- 80a36065-cad6-4380-987d-369f14527bbd
SPMLib ------- feb89e5b-d4ba-4f56-a328-01558d50086b
SPDynamicData ------- e40f8203-b39d-425a-a957-714852e33b79
SPListViewExtensibility ------- d37b65ee-c7d8-4570-bc74-2b294ff3b380
SPApplicationBase ------- 4df9bb86-ab0a-4aab-ab5f-48bf167048fb
SPExtensionBase ------- 0773bd53-a69e-4293-87e6-ba80ea4d614b
SPDragZone ------- f7fa85fe-da91-45cb-9813-5c31106cba7b
SPDialog ------- c0c518b8-701b-4f6f-956d-5782772bb731
SPSearchExtensibility ------- 4958ea79-6ff3-4480-8291-0932dd010869

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle
gulp package-solution

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

Fluent UI Toggle Switch Control in the SharePoint Framework (SPFx) Field Customizer Extension

This article provides steps to implement the Fluent UI Toggle Switch Control in the SharePoint Framework (SPFx) Field Customizer Extension, generally, The toggle switch represents a physical switch that allows users to turn things on or off, like a light switch. Use toggle switch controls to present users with two mutually exclusive options (such as on/off), where choosing an option provides immediate results. In this article, we using the toggle control to change the SharePoint yes/no field value in the SharePoint list view

Create a new extension project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Accept the default value of field-extension as your solution name, and then select Enter.
Select SharePoint Online only (latest), and select Enter.
Select Use the current folder, and select Enter.
Select N to not allow solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select Extension as the client-side component type to be created.
Select Field Customizer as the extension type to be created

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install @pnp/sp --save

Import the library into your application, update constructor, and access the root sp object in render for PnPjs libraries. For this you have to add the contructor for react component

  constructor(props: ISpfxExtensionFluentuiToggleProps) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
  }

Configure the custom properties

In the react component properties interface add some more props for transfer values from BaseFieldCustomizer to React component

export interface ISpfxExtensionFluentuiToggleProps {
  text: string;
  listitemid: string;
  listname: string;
  context: any;
}

Add some import statements to import the types you defined earlier link pnp sp imports.

import { Log } from '@microsoft/sp-core-library';
import { override } from '@microsoft/decorators';
import { Toggle } from 'office-ui-fabric-react/lib/Toggle';
import * as React from 'react';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';
import styles from './SpfxExtensionFluentuiToggle.module.scss';
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";

Replace this render function with the following code.

  @override
  public render(): React.ReactElement<{}> {
    let dvalue = false;
    if (this.props.text == 'Yes')
      dvalue = true;
    return (
      <div className={styles.cell}>
        <Toggle label="" onText="Active" offText="Inactive" onChange={this._onChange} defaultChecked={dvalue} />
      </div>
    );
  }

place the below code inside the react component code, this event function using PnPjs to update in the toggle control change event

  @autobind
  private async _onChange(ev: React.MouseEvent<HTMLElement>, checked: boolean) {
    console.log('toggle is ' + (checked ? 'checked' : 'not checked'));
    let list = sp.web.lists.getByTitle(this.props.listname);

    const i = await list.items.getById(+this.props.listitemid).update({
      Active: checked
    });
  }

Also you have to change the feild value, feild group name and feild type.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
     <Field ID="{8a2312ff-d669-4861-8341-ab4b58f23f13}"
            Name="SPFxActive"
            DisplayName="Active"
            Type="Boolean"
            Required="FALSE"
            Group="SPFx Columns"
            ClientSideComponentId="60320897-6b87-4b93-a7a4-9df418002080">
            <Default>FALSE</Default>
    </Field>
</Elements>

Debug the Field Customizer Extension

In the config folder we have to change some values in the server.json, you can find there are two set of two set of configuration, this will requred only when we debug this in many lists or tenant. in the below code you can find the word of Active this should be your field name and rest everything leave as it is. replace the list list where you going to debug the Field Customizer

{
  "$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
  "port": 4321,
  "https": true,
  "serveConfigurations": {
    "default": {
      "pageUrl": "https://ravichandran.sharepoint.com/sites/TheLanding/Lists/Sales/AllItems.aspx",
      "fieldCustomizers": {
        "Active": {
          "id": "60320897-6b87-4b93-a7a4-9df418002080",
          "properties": {
            "sampleText": "Value"
          }
        }
      }
    }
  }
}

Run below comment

gulp serve

This will redairected to the list you have mention in the server.json file, and Accept the loading of debug manifests by selecting Load debug scripts when prompted.

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle
gulp package-solution

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. goto the site content and select add app and search your app and select to install.

Goto the list settings and Under Columns, select Add from existing site columns

Under the SPFx Columns group, select the Percentage field that was provisioned from the solution package, and then select OK. now you can access your feild Customized column in the default list view

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

Tree view navigation using PnP Treeview control in the SharePoint Framework (SPFx) web part

This article provides steps to implement the Tree view navigation using PnP Treeview control in the SharePoint Framework (SPFx), generally, Treeview control allows to present a hierarchical view of information. Each tree item can have a number of subitems. This is often visualized by an indentation in a list. A tree item can be expanded to reveal subitems (if exist), and collapsed to hide subitems. in this article, we building the dynamic treeview navigation and data stored in the SharePoint list  

Create a new web part project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install @pnp/sp --save
npm install @pnp/spfx-controls-react --save --save-exact

Import the library into your application, update constructor, and access the root sp object in render for PnPjs libraries.

sp.setup({spfxContext: this.props.spcontect});

Configure the custom properties

Create a new source code file under the src\webparts\<Webpart name>\components\ folder of the solution. Create the new file I<web part name>State.ts and use it to create a TypeScript Interface

import { ITreeItem } from "@pnp/spfx-controls-react/lib/TreeView";

export interface ISpfxPnpTreeviewState {
  TreeLinks: ITreeItem[];
}

In addition, you need to update the render method of the client-side web part to create a properly configured instance of the React component for rendering. The following code shows the updated method definition.

  public render(): void {
    const element: React.ReactElement<ISpfxPnpTreeviewProps> = React.createElement(
      SpfxPnpTreeview,
      {
        description: this.properties.description,
        context:this.context
      }
    );
    ReactDom.render(element, this.domElement);
  }

Update the tsx file located under the components. First, add some import statements to import the types you defined earlier. Notice the import for I<web part name>Props and I<web part name>State. There are also some imports for the PnP components used to render the UI of the PnP React component and pnp sp imports.

import * as React from 'react';
import styles from './SpfxPnpTreeview.module.scss';
import { ISpfxPnpTreeviewProps } from './ISpfxPnpTreeviewProps';
import { ISpfxPnpTreeviewState } from './ISpfxPnpTreeviewState';
import { TreeView, ITreeItem, TreeViewSelectionMode, TreeItemActionsDisplayMode } from "@pnp/spfx-controls-react/lib/TreeView";
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxPnpTreeviewProps> {
    return (
      <div className={styles.spfxPnpTreeview}>
        <TreeView
          items={this.state.TreeLinks}
          defaultExpanded={false}
          selectionMode={TreeViewSelectionMode.None}
          selectChildrenIfParentSelected={true}
          showCheckboxes={false}
          treeItemActionsDisplayMode={TreeItemActionsDisplayMode.Buttons}
          onExpandCollapse={this.onTreeItemExpandCollapse}
          onRenderItem={this.renderCustomTreeItem} />
      </div>
    );
  }

Update the React component type declaration and add a constructor, as shown in the following example.

export default class SpfxPnpTreeview extends React.Component<ISpfxPnpTreeviewProps, ISpfxPnpTreeviewState> {
  constructor(props: ISpfxPnpTreeviewProps) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
    this.state = {
      TreeLinks: []
    }
    this._getLinks();
  }

place the below code inside the react component code, these functions using PnPjs to get links from the SharePoint document list

  private async _getLinks() {
    const allItems: any[] = await sp.web.lists.getByTitle("TreeLinks").items.getAll();
    var treearr: ITreeItem[] = [];
    allItems.forEach(function (v, i) {
      if (v["ParentId"] == null) {
        const tree: ITreeItem = {
          key: v.Id,
          label: v["Title"],
          data: v["Link"],
          children: []
        }
        treearr.push(tree);
      }
      else {
        const tree: ITreeItem = {
          key: v.Id,
          label: v["Title"],
          data: v["Link"]
        }
        var treecol: Array<ITreeItem> = treearr.filter(function (value) { return value.key == v["ParentId"] })
        if (treecol.length != 0) {
          treecol[0].children.push(tree);
        }
      }
      console.log(v);
    });
    console.log(treearr);
    this.setState({ TreeLinks: treearr });
  }
  private renderCustomTreeItem(item: ITreeItem): JSX.Element {
    return (
      <span>
        <a href={item.data} target={'_blank'}>
          {item.label}
        </a>
      </span>
    );
  }
  
private onTreeItemExpandCollapse(item: ITreeItem, isExpanded: boolean) {
    console.log((isExpanded ? "Item expanded: " : "Item collapsed: ") + item);
  }

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle
gulp package-solution

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

PnP listview and contextual menu in the SharePoint Framework (SPFx) web part

This article provide steps to implement the PnP Listview with contextual menu in the SharePoint Framework (SPFx), generally Listview control can be used to make fully custom list view for SharePoint List or Library and the contextual menu helps provide options to manages file or list item.

Create a new web part project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install @pnp/sp --save
npm install @pnp/spfx-controls-react --save --save-exact
npm install moment --save

Import the library into your application, update constructor, and access the root sp object in render for PnPjs libraries.

sp.setup({spfxContext: this.props.spcontect});

Configure the custom properties

Create a new source code file under the src\webparts\<Webpart name>\components\ folder of the solution. Create the new file I<web part name>State.ts and use it to create a TypeScript Interface

import { IViewField } from "@pnp/spfx-controls-react/lib/ListView";

export interface ISpfxPnpListviewContextualmenuState {
  items: any[];
  viewFields: IViewField[];
}

In addition, you need to update the render method of the client-side web part to create a properly configured instance of the React component for rendering. The following code shows the updated method definition.

  public render(): void {
    const element: React.ReactElement<ISpfxPnpListviewContextualmenuProps> = React.createElement(
      SpfxPnpListviewContextualmenu,
      {
        description: this.properties.description,
        context:this.context
      }
    );
    ReactDom.render(element, this.domElement);
  }

Update the tsx file under the components. First, add some import statements to import the types you defined earlier. Notice the import for I<web part name>Props and I<web part name>State. There are also some imports for the PnP components used to render the UI of the PnP React component and pnp sp imports.

import * as React from 'react';
import * as moment from 'moment';
import styles from './SpfxPnpListviewContextualmenu.module.scss';
import { ISpfxPnpListviewContextualmenuProps } from './ISpfxPnpListviewContextualmenuProps';
import { ISpfxPnpListviewContextualmenuState } from './ISpfxPnpListviewContextualmenuState';
import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";
import { sp } from "@pnp/sp";
import { autobind } from 'office-ui-fabric-react/lib/Utilities';
import "@pnp/sp/webs";
import "@pnp/sp/files";
import "@pnp/sp/folders";
import { IfilemenuProps, filemenu } from './filemenu';

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxPnpListviewContextualmenuProps> {
    return (
      <div className={styles.spfxPnpListviewContextualmenu}>
        <ListView
          items={this.state.items}
          viewFields={this.state.viewFields}
          iconFieldName="ServerRelativeUrl"
          compact={true}
          selectionMode={SelectionMode.multiple}
          selection={this._getSelection}
          showFilter={true}
          filterPlaceHolder="Search..." />
      </div>
    );
  }

Adding ContextualMenu component

We have to create a new component for ContextualMenu, this ContextualMenu is from the Microsoft fluentui

import * as React from 'react';
import { IconButton } from 'office-ui-fabric-react';
import { ContextualMenuItemType } from 'office-ui-fabric-react/lib/ContextualMenu';
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import { autobind } from 'office-ui-fabric-react/lib/Utilities';

export interface IfilemenuProps {
    item: any;
    context: any;
    ondatachange: any;
}


export class filemenu extends React.Component<IfilemenuProps, {}> {

    public constructor(props: IfilemenuProps) {
        super(props);
        sp.setup({
            spfxContext: this.props.context
        });
        this.state = {
            panelOpen: false
        };
    }

    public render() {
        return (
            <div>
                <IconButton id='ContextualMenuButton1'
                    text=''
                    width='30'
                    split={false}
                    iconProps={{ iconName: 'MoreVertical' }}
                    menuIconProps={{ iconName: '' }}
                    menuProps={{
                        shouldFocusOnMount: true,
                        items: [
                            {
                                key: 'action1',
                                name: 'Open in new tab',
                                onClick: this.handleClick.bind(this, "open", this.props.item)
                            },
                            {
                                key: 'divider_1',
                                itemType: ContextualMenuItemType.Divider
                            },
                            {
                                key: 'action2',
                                name: 'Download',
                                onClick: this.handleClick.bind(this, "download", this.props.item)
                            },
                            {
                                key: 'action3',
                                name: 'Delete',
                                onClick: this.handleClick.bind(this, "delete", this.props.item)
                            },
                            {
                                key: 'disabled',
                                name: 'Disabled action',
                                disabled: true,
                                onClick: () => console.error('Disabled action should not be clickable.')
                            }
                        ]
                    }} />
            </div>
        );
    }

    @autobind
    private async handleClick(actionType: string, seletedfile: any, event) {
        if (actionType === 'open') {
            window.open(
                window.location.protocol + "//" + window.location.host + seletedfile.ServerRelativeUrl + "?web=1",
                '_blank'
            );
        }
        else if (actionType === 'download') {
            window.open(
                window.location.protocol + "//" + window.location.host + seletedfile.ServerRelativeUrl + "?web=0",
                '_blank'
            );
        }
        else if (actionType === 'delete') {
            let list = sp.web.lists.getByTitle("Policies");
            await list.items.getById(seletedfile["ListItemAllFields.ID"]).delete();
            this.props.ondatachange();
        }
    }
}

Update the React component type declaration and add a constructor, as shown in the following example and call the ContextualMenu component as the list view column.

export default class SpfxPnpListviewContextualmenu extends React.Component<ISpfxPnpListviewContextualmenuProps, ISpfxPnpListviewContextualmenuState> {
  constructor(props: ISpfxPnpListviewContextualmenuProps, state: ISpfxPnpListviewContextualmenuState) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
    var _viewFields: IViewField[] = [
      {
        name: "Name",
        linkPropertyName: "ServerRelativeUrl",
        displayName: "Name",
        sorting: true,
        minWidth: 250,
      },
      {
        name: "",
        sorting: false,
        maxWidth: 40,
        render: (rowitem: any) => {
          const element: React.ReactElement<IfilemenuProps> = React.createElement(
            filemenu,
            {
              item: rowitem,
              context: this.props.context,
              ondatachange: this._getfiles
            }
          );
          return element;
        }
      },
      {
        name: "Author.Title",
        displayName: "Author",
        sorting: false,
        minWidth: 180,
        render: (item: any) => {
          const authoremail = item['Author.UserPrincipalName'];
          return <a href={'mailto:' + authoremail}>{item['Author.Title']}</a>;
        }
      },
      {
        name: "TimeCreated",
        displayName: "Created",
        minWidth: 150,
        render: (item: any) => {
          const created = item["TimeCreated"];
          if (created) {
            const createdDate = moment(created);
            return <span>{createdDate.format('DD/MM/YYYY HH:mm:ss')}</span>;
          }
        }
      }
    ];
    this.state = { items: [], viewFields: _viewFields };
    this._getfiles();
  }

place the below code inside the react component code, these functions using PnPjs to get files from the SharePoint document library

  @autobind
  public async _getfiles() {
    const allItems: any[] = await sp.web.getFolderByServerRelativeUrl("/sites/TheLanding/Policies").files.select().expand("ListItemAllFields,Author").get();
    this.setState({ items: allItems });
  }

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle
gulp package-solution

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!