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

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