Tag: FluentUI

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

Fluent UI Message bar in the SharePoint Framework (SPFx) web part

This article provides steps to implement the Fluent UI Message bar in the SharePoint Framework (SPFx) web part, generally a MessageBar is an area at the top of a primary view that displays relevant status information. You can use a MessageBar to tell the user about a situation that does not require their immediate attention and therefore does not need to block other activities.

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 .

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 ISpfxFluentuiMessagebarState {
  InfoMessage: boolean;
  ErrorMessage:boolean;
  AccessMessage:boolean;
  WarningMessage:boolean;
  SuccessQuestion:boolean;
  WarningQuestion:boolean;
  WarningLongMessage:boolean;
}

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 './SpfxFluentuiMessagebar.module.scss';
import { ISpfxFluentuiMessagebarProps } from './ISpfxFluentuiMessagebarProps';
import { ISpfxFluentuiMessagebarState } from './ISpfxFluentuiMessagebarState';
import {
  MessageBarButton,
  Link,
  Stack,
  MessageBar,
  MessageBarType,
  DefaultButton, PrimaryButton, IStackTokens
} from 'office-ui-fabric-react';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';

Replace this render function with the following code.

public render(): React.ReactElement<ISpfxFluentuiMessagebarProps> {
    return (
      <div className={styles.spfxFluentuiMessagebar}>
        {(this.state.InfoMessage) ? <div><InfoMessage /><br /></div> : ''}
        {(this.state.ErrorMessage) ? <div><ErrorMessage /><br /></div> : ''}
        {(this.state.AccessMessage) ? <div><AccessMessage /><br /></div> : ''}
        {(this.state.WarningMessage) ? <div><WarningMessage /><br /></div> : ''}
        {(this.state.SuccessQuestion) ? <div><SuccessQuestion /><br /></div> : ''}
        {(this.state.WarningQuestion) ? <div><WarningQuestion /><br /></div> : ''}
        {(this.state.WarningLongMessage) ? <div><WarningLongMessage /><br /></div> : ''}
        <br />
        <br />
        <Stack horizontal tokens={stackTokens}>
          <PrimaryButton text="Show Info Message" onClick={() => this._showMessageClicked('InfoMessage')} />
          <PrimaryButton text="Show Error Message" onClick={() => this._showMessageClicked('ErrorMessage')} />
          <PrimaryButton text="Show Access Message" onClick={() => this._showMessageClicked('AccessMessage')} />
        </Stack>
        <br />
        <br />
        <Stack horizontal tokens={stackTokens}>
          <PrimaryButton text="Show Warning Message" onClick={() => this._showMessageClicked('WarningMessage')} />
          <PrimaryButton text="Show Success with Question Message" onClick={() => this._showMessageClicked('SuccessQuestion')} />
          <PrimaryButton text="Show Warning with Question Message" onClick={() => this._showMessageClicked('WarningQuestion')} />
        </Stack>
        <br />
        <br />
        <Stack horizontal tokens={stackTokens}>
          <PrimaryButton text="Show Long Message" onClick={() => this._showMessageClicked('WarningLongMessage')} />
          <PrimaryButton text="Show info message and hide after 5 sec" onClick={this._showandhideMessageClicked} />
          <DefaultButton text="Hide All Message" onClick={this._hideMessageClicked} />
        </Stack>

      </div>
    );
  }

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

export default class SpfxFluentuiMessagebar extends React.Component<ISpfxFluentuiMessagebarProps, ISpfxFluentuiMessagebarState> {
  constructor(props: ISpfxFluentuiMessagebarProps, state: ISpfxFluentuiMessagebarState) {
    super(props);
    this.state = ({
      InfoMessage: false,
      ErrorMessage: false,
      AccessMessage: false,
      WarningMessage: false,
      SuccessQuestion: false,
      WarningQuestion: false,
      WarningLongMessage: false,
    })
  }

place the below code inside the react component class, these functions for message bar the events

 @autobind
  private _showMessageClicked(messagetype: string): void {
    if (messagetype == 'InfoMessage')
      this.setState({ InfoMessage: true })
    else if (messagetype == 'ErrorMessage')
      this.setState({ ErrorMessage: true })
    else if (messagetype == 'AccessMessage')
      this.setState({ AccessMessage: true })
    else if (messagetype == 'WarningMessage')
      this.setState({ WarningMessage: true })
    else if (messagetype == 'SuccessQuestion')
      this.setState({ SuccessQuestion: true })
    else if (messagetype == 'WarningQuestion')
      this.setState({ WarningQuestion: true })
    else if (messagetype == 'WarningLongMessage')
      this.setState({ WarningLongMessage: true })
  }

  @autobind
  private _hideMessageClicked(): void {
    this.setState({
      InfoMessage: false, ErrorMessage: false, AccessMessage: false, WarningMessage: false,
      SuccessQuestion: false, WarningQuestion: false, WarningLongMessage: false
    })
  }

  @autobind
  private _showandhideMessageClicked(): void {
    this.setState({ InfoMessage: true })
    setTimeout(function () {
      this.setState({ InfoMessage: false })
    }.bind(this), 5000);
  }

These all have to next to imports, but inside the react component class

const InfoMessage = () => (
  <MessageBar>
    Info/Default MessageBar.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
);
const ErrorMessage = () => (
  <MessageBar
    messageBarType={MessageBarType.error}
    isMultiline={false}
    dismissButtonAriaLabel="Close"
  >
    Error MessageBar with single line, with dismiss button.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
);

const AccessMessage = () => (
  <MessageBar
    messageBarType={MessageBarType.blocked}
    isMultiline={false}
    dismissButtonAriaLabel="Close"
    truncated={true}
    overflowButtonAriaLabel="See more"
  >
    <b>Blocked MessageBar - single line, with dismiss button and truncated text.</b> Truncation is not available if you
    use action buttons or multiline and should be used sparingly. Lorem ipsum dolor sit amet, consectetur adipiscing
    elit. Morbi luctus, purus a lobortis tristique, odio augue pharetra metus, ac placerat nunc mi nec dui. Vestibulum
    aliquam et nunc semper scelerisque. Curabitur vitae orci nec quam condimentum porttitor et sed lacus. Vivamus ac
    efficitur leo. Cras faucibus mauris libero, ac placerat erat euismod et. Donec pulvinar commodo odio sit amet
    faucibus. In hac habitasse platea dictumst. Duis eu ante commodo, condimentum nibh pellentesque, laoreet enim. Fusce
    massa lorem, ultrices eu mi a, fermentum suscipit magna. Integer porta purus pulvinar, hendrerit felis eget,
    condimentum mauris.
  </MessageBar>
);

const WarningMessage = () => (
  <MessageBar
    messageBarType={MessageBarType.severeWarning}
    actions={
      <div>
        <MessageBarButton onClick={() => console.log('Yes clicked')}>Yes</MessageBarButton>
        <MessageBarButton onClick={() => console.log('No clicked')}>No</MessageBarButton>
      </div>
    }
  >
    SevereWarning MessageBar with action buttons which defaults to multiline.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
);

const SuccessQuestion = () => (
  <MessageBar
    actions={
      <div>
        <MessageBarButton onClick={() => console.log('Yes clicked')}>Yes</MessageBarButton>
        <MessageBarButton onClick={() => console.log('No clicked')}>No</MessageBarButton>
      </div>
    }
    messageBarType={MessageBarType.success}
    isMultiline={false}
  >
    Success MessageBar with single line and action buttons.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
);

const WarningQuestion = () => (
  <MessageBar
    messageBarType={MessageBarType.warning}
    isMultiline={false}
    dismissButtonAriaLabel="Close"
    actions={
      <div>
        <MessageBarButton onClick={() => console.log('Action clicked')}>Action</MessageBarButton>
      </div>
    }
  >
    Warning MessageBar content.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
);

const WarningLongMessage = () => (
  <MessageBar
    dismissButtonAriaLabel="Close"
    messageBarType={MessageBarType.warning}
    actions={
      <div>
        <MessageBarButton>Yes</MessageBarButton>
        <MessageBarButton>No</MessageBarButton>
      </div>
    }
  >
    <b>Warning defaults to multiline</b>. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi luctus, purus a
    lobortis tristique, odio augue pharetra metus, ac placerat nunc mi nec dui. Vestibulum aliquam et nunc semper
    scelerisque. Curabitur vitae orci nec quam condimentum porttitor et sed lacus. Vivamus ac efficitur leo. Cras
    faucibus mauris libero, ac placerat erat euismod et. Donec pulvinar commodo odio sit amet faucibus. In hac habitasse
    platea dictumst. Duis eu ante commodo, condimentum nibh pellentesque, laoreet enim. Fusce massa lorem, ultrices eu
    mi a, fermentum suscipit magna. Integer porta purus pulvinar, hendrerit felis eget, condimentum mauris.
    <Link href="www.bing.com" target="_blank">
      Visit our website.
    </Link>
  </MessageBar>
);

const stackTokens: IStackTokens = { childrenGap: 40 };

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

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