Tag: PnPjs

React Hooks in SPFx

This article provides steps to use the react hooks in the SharePoint Framework (SPFx) projects, generally, Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes. here we walkthrough react state, props, event and async functions in the FunctionComponent for SPFx.  

Why React Hooks

You can find a lot of reason why we have to use hooks is like Hooks allow you to use local state and other React features without writing a class. But the basic reason is most of them not interested to bind all the events and function to access the state values, also not interested to run super() inside the constructor and etc… 

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

Function Component and react Props

Basically FunctionComponent is replacing the React. Component class. its is much simple, yes, just function that is all. in below example, both serves the same. you can choose either logic based on your convenient.   

you can also find the way to pass the props into your FunctionComponent

import * as React from 'react';
import { ISpfxReactHooksProps } from './ISpfxReactHooksProps';

const SpfxReactHooks: React.FunctionComponent<ISpfxReactHooksProps> = props => {
  return <div>hello from logic 1 {props.description}</div>
}
export default SpfxReactHooks;

Or

import * as React from 'react';
import { ISpfxReactHooksProps } from './ISpfxReactHooksProps';

function simplehooks(props: ISpfxReactHooksProps) {
  return <div>hello from logic 2 {props.description}</div>
}
export default simplehooks;

React State

For use react state, we have to import separately from react and the basic syntax of the state is creating const and pass state variable name first then virtual function name then equal to useState and pass the initial value as a parameter, so inside the dom or in any event you can read and set the value for the state.  

import * as React from 'react';
import { useState } from 'react';
import { ISpfxReactHooksProps } from './ISpfxReactHooksProps';
import { PrimaryButton } from 'office-ui-fabric-react';

function simplehooks(props: ISpfxReactHooksProps) {
  const [firstName, setFistName] = useState("No Name")
  return <div>
    {firstName}
    <br />
    <br />
    <PrimaryButton text="Primary" onClick={() => setFistName('new fist name')} />
  </div>
}

export default simplehooks;

Events

Events can be inline for just change the state values of it can be a separate function, in the below example code you can find both logics 

import * as React from 'react';
import { useState } from 'react';
import { ISpfxReactHooksProps } from './ISpfxReactHooksProps';
import { TextField, PrimaryButton } from 'office-ui-fabric-react';

function simplehooks(props: ISpfxReactHooksProps) {
  const [firstName, setFistName] = useState("No first Name")
  const [lastName, setLastName] = useState("No last Name")

  const _onbtnclick = () => {
    console.log('Changing value')
    setFistName('new fist name')
  }

  const _lastNameChanged = (changedvalue: any) => {
    setLastName(changedvalue)
  }

  return (<div>
    Fullname : {firstName + ' ' + lastName}
    <br />
    <br />
    <TextField label="last name" onChanged={_lastNameChanged} value={lastName} />
    <br />
    <br />
    <PrimaryButton text="change state value" onClick={() => _onbtnclick()} />
  </div>);
}

export default simplehooks;

Async Function

In the React.Component class, we used constructor to call the async functions, in the FunctionComponent we using useEffect to replace constructor. Basically useEffect help to run the code only once while first time loads the page, If you call the async directly then it will make the infinite loop. Also while loop the elements we have to set the unique value as key as shown below example, here we setting Intex as the unique key   

import * as React from 'react';
import { useState, useEffect } from 'react';
import { ISpfxReactHooksProps } from './ISpfxReactHooksProps';
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";

function simplehooks(props: ISpfxReactHooksProps) {
  const [fruits, setfruits] = useState([])

  useEffect(() => {
    sp.setup({
      spfxContext: props.context
    });
    _getListItemsFromSP()
  }, []);

  const _getListItemsFromSP = async () => {
    const allItems: any[] = await sp.web.lists.getByTitle("Fruits").items.getAll();
    let titlevalues: string[] = [];
    allItems.forEach(function (v, i) {
      titlevalues.push(v.Title);
    })
    setfruits(titlevalues);
  }

  console.log(fruits);
  return (<div>
    {fruits.map(function (fruit, i) {
      return <h3 key={i}>{fruit}</h3>
    })}
  </div>);
}

export default simplehooks;

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!!!

Custom Property Pane using Fluent UI Panel in SPFx

These articles provide steps to implement the Custom Property Pane using Fluent UI Panel in the SharePoint Framework (SPFx) web part, generally Fluent UI Panels are modal UI overlays that provide contextual app information. They often request some kind of creation or management action from the user. Panels are paired with the Overlay component, also known as a Light Dismiss. The Overlay blocks interactions with the app view until dismissed either through clicking or tapping on the Overlay or by selecting a close or completion action within the Panel.

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

Configure the custom properties

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

import { IDropdownOption } from 'office-ui-fabric-react';
export interface ISpfxFluentuiPanelState {
  projects: IDropdownOption[];
  showpanel: boolean;
  projectname?: string;
}

Update the <web part name>.tsx file. 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 './SpfxFluentuiPanel.module.scss';
import { ISpfxFluentuiPanelProps } from './ISpfxFluentuiPanelProps';
import { ISpfxFluentuiPanelState } from './ISpfxFluentuiPanelState';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';
import { DefaultButton, PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import { Panel, IDropdownOption, Dropdown, IStackTokens, Stack, IIconProps, TextField, } from 'office-ui-fabric-react';
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
const stackTokens: IStackTokens = { childrenGap: 20 };
const addIcon: IIconProps = { iconName: 'Add' };

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxFluentuiPanelProps> {
    let buttonStyles = { root: { marginRight: 8 } };
    const onRenderFooterContent = () => (
      <div>
        <PrimaryButton onClick={this._saveclick} styles={buttonStyles}>
          Save
        </PrimaryButton>
        <DefaultButton onClick={this._cancelclick}>Cancel</DefaultButton>
      </div>
    );

    return (
      <div className={styles.spfxFluentuiPanel}>
        <Stack tokens={stackTokens} verticalAlign="end">
          <Stack horizontal tokens={stackTokens} verticalAlign="end">
            <Dropdown className={styles.Dropdown}
              placeholder="Select a Project"
              label="Projects"
              options={this.state.projects}
            />
            <DefaultButton text="Project" iconProps={addIcon} onClick={() => this.setState({ showpanel: true, projectname: '' })} />
          </Stack>
        </Stack>
        {this.state.showpanel &&
          <Panel
            headerText={"New Project Name"}
            isOpen={true}
            isBlocking={false}
            closeButtonAriaLabel="Close"
            onRenderFooterContent={onRenderFooterContent}>
            <TextField placeholder={'Enter a new project name'} onChanged={(strproject) => this.setState({ projectname: strproject })}></TextField>
          </Panel>
        }

      </div>
    );
  }

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

export default class SpfxFluentuiPanel extends React.Component<ISpfxFluentuiPanelProps, ISpfxFluentuiPanelState> {
  constructor(props: ISpfxFluentuiPanelProps, state: ISpfxFluentuiPanelState) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
    this.state = { showpanel: false, projects: [] };
    this._getProjects();
  }

Add below event functions and function to get list items from SharePoint to inside the react component

  private async _getProjects() {
    const allItems: any[] = await sp.web.lists.getByTitle("Projects").items.getAll();
    const options: IDropdownOption[] = [];
    allItems.forEach(function (v, i) {
      options.push({ key: v.ID, text: v.Title });
    });
    this.setState({ projects: options });
  }
  @autobind
  private async _saveclick() {
    if (this.state.projectname != '') {
      const iar = await sp.web.lists.getByTitle("Projects").items.add({
        Title: this.state.projectname,
      });
      const projectsarr = this.state.projects;
      projectsarr.push({ key: iar.data.ID, text: this.state.projectname })
      this.setState({ showpanel: false, projects: projectsarr });
    }
    else {
      //here you can add code for show error message if project name is blank
    }
  }

  @autobind
  private _cancelclick() {
    this.setState({ showpanel: false });
  }

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!!!

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!!!

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!!!

PnP Rich Text Editor in the SharePoint Framework (SPFx) webpart

These articles provide steps to implement the PnP Rich Text Editor in the SharePoint Framework (SPFx), generally People picker control provides rich text editing and display capability.

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\spfxPnpDatetimepicker\components\ folder of the solution. Call the new file I<web part name>State.ts and use it to create a TypeScript Interface

export interface ISpfxPnpRichtextState {
  description: string;
  SuccessMessage: 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(): React.ReactElement<ISpfxPnpRichtextProps> {
    let tamil = (this.state.description === '') ? 'Dummy' : this.state.description;
    return (
      <div className={styles.spfxPnpRichtext}>
        <RichText isEditMode={true} value={this.state.description} onChange={this._onTextChange} />
        <br></br>
        <button className={styles.button} onClick={this._updateDescription}>Save</button>
        <br></br>
        <br></br>
        <label className={styles.label}>{this.state.SuccessMessage}</label>
      </div>
    );
  }

Update the SpfxPnpRichtext.tsx file. 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 './SpfxPnpRichtext.module.scss';
import { ISpfxPnpRichtextProps } from './ISpfxPnpRichtextProps';
import { ISpfxPnpRichtextState } from './ISpfxPnpRichtextState';
import { sp } from "@pnp/sp";
import { RichText } from "@pnp/spfx-controls-react/lib/RichText";
import { autobind } from 'office-ui-fabric-react/lib/Utilities';
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxPnpRichtextProps> {
    let tamil = (this.state.description === '') ? 'Dummy' : this.state.description;
    return (
      <div className={styles.spfxPnpRichtext}>
        <RichText isEditMode={true} value={this.state.description} onChange={this._onTextChange} />
        <br></br>
        <button className={styles.button} onClick={this._updateDescription}>Save</button>
        <br></br>
        <br></br>
        <label className={styles.label}>{this.state.SuccessMessage}</label>
      </div>
    );
  }

In the selected Item event get the values and set it into the state

 @autobind
  private async _getDescription() {
    const item: any = await sp.web.lists.getByTitle("Teams").items.getById(1).get();
    this.setState({ description: item.Description });
  }

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

export default class SpfxPnpRichtext extends React.Component<ISpfxPnpRichtextProps, ISpfxPnpRichtextState> {
  constructor(props: ISpfxPnpRichtextProps, state: ISpfxPnpRichtextState) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
    this.state = { SuccessMessage: '', description: '' };
    this._getDescription();
  }

place the below code inside the react component code, these functions using PnPjs to get date from the SharePoint list item and save the values as well

 @autobind
  private async _updateDescription() {
    console.log(this.state.description);
    const updatedItem = await sp.web.lists.getByTitle("Teams").items.getById(1).update(
      {
        Description: this.state.description
      });
    this.setState({ SuccessMessage: 'Successfully saved' });
  }

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!!!