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

Popup Documents using PnP IFrameDialog Control in SPFx

This article provides steps to implement the Popup Documents using PnP IFrameDialog Control in the SharePoint Framework (SPFx) Field Customizer Extension, generally, PnP IFrameDialog control renders a Dialog with an iframe as content. In this article, we opening documents in the popup from SharePoint document library

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/spfx-controls-react --save --save-exact

Configure the custom properties

In the react component properties interface add some more props for transfer values from BaseFieldCustomizer to React component, also create one state interface

export interface ISpfxPnpIframedialogExtensionProps {
  FileName: string;
  FileURL: string;
}

export interface ISpfxPnpIframedialogExtensionState {
  shouldhide: boolean;
}

Add some import statements to import

import { Log } from '@microsoft/sp-core-library';
import { override } from '@microsoft/decorators';
import * as React from 'react';
import { IFrameDialog } from "@pnp/spfx-controls-react/lib/IFrameDialog";
import { DialogType, IconButton, IIconProps } from 'office-ui-fabric-react';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';
import styles from './SpfxPnpIframedialogExtension.module.scss';

Replace this render function with the following code.

  @override
  public render(): React.ReactElement<{}> {
    return (
      <div className={styles.cell}>
        <IconButton iconProps={emojiIcon} onClick={this._alertClicked} />
        <IFrameDialog
          url={this.props.FileURL}
          hidden={this.state.souldhide}
          onDismiss={() => this.setState({ shouldhide: true })}
          modalProps={{
            isBlocking: false
          }}
          dialogContentProps={{
            type: DialogType.close,
            showCloseButton: true
          }}
          width={'1000px'}
          height={'600px'} />

      </div>
    );
  }

place the below code inside the react component code, this event function set values in the react state

  @autobind
  private _alertClicked() {
    this.setState({ shouldhide: false });
  }

Also you have to change the feild value, feild group name and feild type. in the file of elements.xml located under sharepoint\assets\

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <Field ID="{c78fa9c1-6875-47d4-9c47-f9da19edc564}" Name="SPFxPopup" DisplayName="Popup" Type="Calculated" Min="0" Required="FALSE" Group="SPFx Columns" ClientSideComponentId="23ef2026-7f63-40d4-9b6a-11bbea6c1ec2">
        <Formula>="value"</Formula>
    </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 Popup 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/Policies/Forms/AllItems.aspx",
      "fieldCustomizers": {
        "Popup": {
          "id": "23ef2026-7f63-40d4-9b6a-11bbea6c1ec2",
          "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 Popup 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!!!

Multi-Select Lookup Field Managed Using Fluent UI Dropdown in SPFx

These articles provide steps to implement the Multi-Select Lookup Field Managed Using Fluent UI Dropdown in the SharePoint Framework (SPFx) web part, generally Fluent UI Dropdown is a list in which the selected item is always visible, and the others are visible on demand by clicking a drop-down button. They are used to simplify the design and make a choice within the UI. When closed, only the selected item is visible. When users click the drop-down button, all the options become visible. To change the value, users open the list and click another value or use the arrow keys (up and down) to select a new value. Here we save and retrive values multi-select lookup field values 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

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 { Dropdown, DropdownMenuItemType, IDropdownOption, IDropdownStyles } from 'office-ui-fabric-react/lib/Dropdown';

export interface ISpfxFluentuiDropdownState {
  projectlookupvalues: IDropdownOption[];
  salestitle: string;
  seletedprojects: number[];
}

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 './SpfxFluentuiDropdown.module.scss';
import { ISpfxFluentuiDropdownProps } from './ISpfxFluentuiDropdownProps';
import { ISpfxFluentuiDropdownState } from './ISpfxFluentuiDropdownState';
import { Dropdown, IDropdownOption, TextField, PrimaryButton } from 'office-ui-fabric-react';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';
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<ISpfxFluentuiDropdownProps> {
    return (
      <div className={styles.spfxFluentuiDropdown}>
        <TextField
          className={styles.fixedwidth}
          label="Title" value={this.state.salestitle} onChanged={(titlevalue) => this.setState({ salestitle: titlevalue })} />
        {this.state.seletedprojects == null ? '' : <Dropdown
          placeholder="Select projects"
          label="Projects"
          onChange={this.projects_selection}
          multiSelect
          options={this.state.projectlookupvalues}
          className={styles.fixedwidth}
          defaultSelectedKeys={this.state.seletedprojects}
        />}

        <br />
        <PrimaryButton text="Save" onClick={this._savesales} />
      </div>
    );
  }

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

export default class SpfxFluentuiDropdown extends React.Component<ISpfxFluentuiDropdownProps, ISpfxFluentuiDropdownState> {
  constructor(props: ISpfxFluentuiDropdownProps, state: ISpfxFluentuiDropdownState) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
    this.state = ({ projectlookupvalues: [], salestitle: '', seletedprojects: null })
    this._getLookupvalues();
  }

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

  @autobind
  private async _getLookupvalues() {
    const allItems: any[] = await sp.web.lists.getByTitle("Projects").items.getAll();

    let projectarr: IDropdownOption[] = [];
    allItems.forEach(project => {
      projectarr.push({ key: project.ID, text: project.Title });
    })
    this.setState({
      projectlookupvalues: projectarr
    });
    this._getSalesInfo();
  }

  @autobind
  private async _getSalesInfo() {
    const salesitem: any = await sp.web.lists.getByTitle("Sales").items.getById(1).get();
    console.log(salesitem)
    this.setState({ seletedprojects: salesitem.ProjectsId, salestitle: salesitem.Title })
  }

  @autobind
  private async _savesales() {
    await sp.web.lists.getByTitle("Sales").items.getById(1).update({
      Title: this.state.salestitle,
      ProjectsId: {
        results: this.state.seletedprojects
      }
    });
  }

  @autobind
  private projects_selection(event: React.FormEvent<HTMLDivElement>, item: IDropdownOption) {
    if (item.selected) {
      let seleteditemarr = this.state.seletedprojects;
      seleteditemarr.push(+item.key);
      this.setState({ seletedprojects: seleteditemarr });
    }
    else {
      let seleteditemarr = this.state.seletedprojects;
      let i = seleteditemarr.indexOf(+item.key);
      if (i >= 0) {
        seleteditemarr.splice(i, 1);
      }
      this.setState({ seletedprojects: seleteditemarr });
    }
  }

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 ListItem Attachments control in the SharePoint Framework (SPFx) web part

These articles provide steps to implement the PnP ListItem Attachments control in the SharePoint Framework (SPFx) web part, generally List Item attachment control allows you to manage list item attachments, you can add or delete associated attachments. The attachments are listed in tile view.

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/spfx-controls-react --save --save-exact

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

export interface ISpfxPnpListitemattachmentsState {
  SeletedList: string;
  SelectedItem: number;
}

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 './SpfxPnpListitemattachments.module.scss';
import { ISpfxPnpListitemattachmentsProps } from './ISpfxPnpListitemattachmentsProps';
import { ISpfxPnpListitemattachmentsState } from './ISpfxPnpListitemattachmentsState';
import { ListPicker, ListItemPicker } from "@pnp/spfx-controls-react/lib";
import { autobind } from 'office-ui-fabric-react/lib/Utilities';
import { SpfxAttachmentControl } from '../../spfxPnpListitemattachments/components/SpfxAttachmentControl';

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxPnpListitemattachmentsProps> {
    let attaprops: any = [];
    attaprops = ({ SeletedList: this.state.SeletedList, SelectedItem: this.state.SelectedItem, context: this.props.context });
    return (
      <div className={styles.spfxPnpListitemattachments}>
        <ListPicker context={this.props.context}
          label="Select your list"
          placeHolder="Select your list"
          baseTemplate={100}
          includeHidden={false}
          multiSelect={false}
          onSelectionChanged={this.onListPickerChange} />
        <br></br>
        <label>Search List Item</label>
        <ListItemPicker listId={this.state.SeletedList}
          columnInternalName='Title'
          keyColumnInternalName='Id'
          itemLimit={1}
          onSelectedItem={this.onSelectedItem}
          context={this.props.context} />
        <br></br>
        <SpfxAttachmentControl {...attaprops}></SpfxAttachmentControl>
      </div>
    );
  }

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

export default class SpfxPnpListitemattachments extends React.Component<ISpfxPnpListitemattachmentsProps, ISpfxPnpListitemattachmentsState> {
  constructor(props: ISpfxPnpListitemattachmentsProps, state: ISpfxPnpListitemattachmentsState) {
    super(props);
    this.state = { SeletedList: "", SelectedItem: null };
  }

Add below event functions inside the react component

  @autobind
  private onListPickerChange(selectedlist: string) {
    this.setState({
      SeletedList: selectedlist
    });
  }

  @autobind
  private onSelectedItem(data: { key: string; name: string }[]) {
    if (data.length == 0) {
      this.setState({ SelectedItem: null });
    }
    else
      for (const item of data) {
        this.setState({ SelectedItem: +item.key })
      }
  }

We have created PnP list item attachments as separate component, due to some issue in the control.

import * as React from 'react';
import { ListItemAttachments } from "@pnp/spfx-controls-react/lib";
import styles from './SpfxPnpListitemattachments.module.scss';

export interface ISpfxAttachmentControlProps {
    SeletedList: string;
    SelectedItem: number;
    context: any | null;
}

export class SpfxAttachmentControl extends React.Component<ISpfxAttachmentControlProps, {}> {
    public render(): React.ReactElement<ISpfxAttachmentControlProps> {
        return (
            <div className={styles.spfxPnpListitemattachments}>
                {(this.props.SelectedItem == null) ? '' :
                    <div><label>Attachments</label>
                        <ListItemAttachments listId={this.props.SeletedList}
                            itemId={this.props.SelectedItem}
                            context={this.props.context}
                            disabled={false} /></div>
                }
            </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.

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

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