Author: Ravichandran Krishnasamy

Consume the Microsoft Graph API using PnP in SPFx

This article provides steps to consume the Microsoft Graph API using PnP Graph package in the SharePoint Framework (SPFx) web part, we can access Graph API in many ways across the all the logic this is the easiest. we going to get people information using Graph API, this is the same logic can use to access any of the Office 365 data using PnP Graph. 

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 favourite 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/graph --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

export interface ISpfxPnpGraphState {
  description: string;
  users:IUserItem[];
}

export interface IUserItem {
  displayName: string;
  url: string;
  userPrincipalName: string;
  profileImageSrc:string;
  jobTitle: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 './SpfxPnpGraph.module.scss';
import { ISpfxPnpGraphProps } from './ISpfxPnpGraphProps';
import { ISpfxPnpGraphState, IUserItem } from './ISpfxPnpGraphState';
import {
  DocumentCardActivity
} from 'office-ui-fabric-react/lib/DocumentCard';
import { graph } from "@pnp/graph";
import "@pnp/graph/users"
import "@pnp/graph/contacts"

Replace this render function with the following code.

  private async _getPeople() {
    var users: Array<IUserItem> = new Array<IUserItem>();
    const peoplecol = await graph.me.people.top(15)();
    peoplecol.map((people: any) => {
      users.push({
        displayName: people.displayName,
        url: this.props.context.pageContext.web.absoluteUrl + '/PersonImmersive.aspx?accountname=i%3A0%23%2Ef%7Cmembership%7C' + people.userPrincipalName,
        userPrincipalName: people.userPrincipalName,
        profileImageSrc: this.props.context.pageContext.web.absoluteUrl + "/_layouts/15/userphoto.aspx?size=L&username=" + people.userPrincipalName,
        jobTitle: people.jobTitle
      });
    });
    this.setState({ users: users })
  }

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

export default class SpfxPnpGraph extends React.Component<ISpfxPnpGraphProps, ISpfxPnpGraphState> {
  constructor(props: ISpfxPnpGraphProps, state: ISpfxPnpGraphState) {
    super(props);
    graph.setup({
      spfxContext: this.props.context
    });
    this.state = { description: '', users: [] }
    this._getPeople()
  }

Add below event function inside the react component for upload files to SharePoint Library

  private async _getPeople() {
    var users: Array<IUserItem> = new Array<IUserItem>();
    const peoplecol = await graph.me.people.top(15)();
    peoplecol.map((people: any) => {
      users.push({
        displayName: people.displayName,
        url: this.props.context.pageContext.web.absoluteUrl + '/PersonImmersive.aspx?accountname=i%3A0%23%2Ef%7Cmembership%7C' + people.userPrincipalName,
        userPrincipalName: people.userPrincipalName,
        profileImageSrc: this.props.context.pageContext.web.absoluteUrl + "/_layouts/15/userphoto.aspx?size=L&username=" + people.userPrincipalName,
        jobTitle: people.jobTitle
      });
    });
    this.setState({ users: users })
  }

Configuring Permission request

Have to configure the Graph API access request, it totally based on the what data you want to access using Graph API. In the package-soltion.ts file which located under config folder. In this file you have to add webApiPermissionRequests property in the JSON.

{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
  "solution": {
    "name": "spfx-pnp-graph-client-side-solution",
    "id": "ca39bbbc-8c41-4bef-9043-395bbb53e62e",
    "version": "1.0.0.0",
    "includeClientSideAssets": true,
    "skipFeatureDeployment": true,
    "isDomainIsolated": false,
    "webApiPermissionRequests": [
      {
        "resource": "Microsoft Graph",
        "scope": "People.Read.All"
      }
    ]
  },
  "paths": {
    "zippedPackage": "solution/spfx-pnp-graph.sppkg"
  }
}

If you not sure not exactly what permission you have to configure then the visit the Microsoft graph explorer. In this page you can find the tab called Modify permission, in that tab, you can find what exact permission you have to configure for your API call

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. before you add the package in the page, you have to make sure permission requests are approved under 

https://<tenant>-admin.sharepoint.com/_layouts/15/online/AdminHome.aspx#/webApiPermissionManagement

Sharing is caring!

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

Simple drag and drop files upload zone in SPFx

This article provides steps to implement the Simple drag and drop files upload zone in the SharePoint Framework (SPFx), we have used react-filepond implement this functionality.

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 react-filepond filepond --save
npm i filepond-plugin-image-preview
npm i filepond-plugin-image-exif-orientation

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 ISpfxReactDropzoneState {
  files: any[];
}

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 './SpfxReactDropzone.module.scss';
import { ISpfxReactDropzoneProps } from './ISpfxReactDropzoneProps';
import { ISpfxReactDropzoneState } from './ISpfxReactDropzoneState';
import { 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/files";
import "@pnp/sp/folders";

import { FilePond, registerPlugin } from 'react-filepond';
import 'filepond/dist/filepond.min.css';
import FilePondPluginImageExifOrientation from 'filepond-plugin-image-exif-orientation'
import FilePondPluginImagePreview from 'filepond-plugin-image-preview'
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css'

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxReactDropzoneProps> {
    return (
      <div className={styles.spfxReactDropzone}>
        <FilePond files={this.state.files} allowMultiple={true} onupdatefiles={fileItems => {
          this.setState({
            files: fileItems.map(fileItem => fileItem.file)
          });
        }} />
        <br />
        <PrimaryButton text="Upload" onClick={this._uploadFiles} />
      </div>
    );
  }

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

export default class SpfxReactDropzone extends React.Component<ISpfxReactDropzoneProps, ISpfxReactDropzoneState> {
  constructor(props: ISpfxReactDropzoneProps, state: ISpfxReactDropzoneState) {
    super(props);
    sp.setup({
      spfxContext: this.props.context
    });
    this.state = ({ files: [] });
    registerPlugin(FilePondPluginImageExifOrientation, FilePondPluginImagePreview)
  }

Add below event function inside the react component for upload files to SharePoint Library

  @autobind
  private async _uploadFiles() {
    this.state.files.forEach(function (file, i) {
      // you can adjust this number to control what size files are uploaded in chunks
      if (file.size <= 10485760) {
        // small upload
        const newfile = sp.web.getFolderByServerRelativeUrl("/sites/TheLanding/Books/").files.add(file.name, file, true);
      } else {
        // large upload
        const newfile = sp.web.getFolderByServerRelativeUrl("/sites/TheLanding/Books/").files.addChunked(file.name, file, data => {
        }, true);
      }
    });
    this.setState({ files: [] })
  }

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

Local Weather Forecast in SPFx

This article provides steps to implement the Local Weather Forecast in the SharePoint Framework (SPFx), we use some third party REST API to get the current location based on IP address and we getting local weather forecast using the latitude and latitude, so this web part not required any property configuration, it just automatically picking up the local weather forecast 

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

export interface ISpfxWeatherState {
  skyimage: string;
  location: string;
  weatherid: string;
  temperature: string;
  windspeed: string;
  humidity: 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 './SpfxWeather.module.scss';
import { ISpfxWeatherProps } from './ISpfxWeatherProps';
import { ISpfxWeatherState } from './ISpfxWeatherState';
import { HttpClient, HttpClientResponse } from '@microsoft/sp-http';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxWeatherProps> {
    return (
      <div className={styles.spfxWeather}>
        <img src={this.state.skyimage}></img><br />
        Location: {this.state.location}<br />
        Skies: {this.state.weatherid}<br />
        Temperature: {this.state.temperature}&deg;C<br />
        Wind speed: {this.state.windspeed}<br />
        Humidity: {this.state.humidity}<br />
      </div>
    );
  }

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

export default class SpfxWeather extends React.Component<ISpfxWeatherProps, ISpfxWeatherState> {
  constructor(props: ISpfxWeatherProps, state: {}) {
    super(props);
    this.state = ({ skyimage: '', location: '', weatherid: '', temperature: '', windspeed: '', humidity: '' })
    this.getWeather();
  }

Add below event functions and function to get local weather forecast

  @autobind
  private async getWeather() {
    console.log(this.props.description)
    const info = await this.props.context.httpClient.get('https://ipinfo.io/json')
    const locinfo = await info.json();
    var locString = locinfo.loc.split(',');
    var latitude = parseFloat(locString[0]);
    var longitude = parseFloat(locString[1]);
    const weather = await this.props.context.httpClient.get('https://cors.5apps.com/?uri=http://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&units=metric&APPID=c3e00c8860695fd6096fe32896042eda')
    const weatherinfo = await weather.json();
    var windSpeedkmh = Math.round(weatherinfo.wind.speed * 3.6);
    var Celsius = Math.round(weatherinfo.main.temp)
    var iconId = weatherinfo.weather[0].icon;
    var weatherURL = "http://openweathermap.org/img/w/" + iconId + ".png";
    this.setState({
      skyimage: weatherURL,
      location: locinfo.city + ', ' + locinfo.region + ', ' + locinfo.country,
      weatherid: weatherinfo.weather[0].description,
      temperature: Celsius.toString(),
      windspeed: windSpeedkmh + ' km/hr',
      humidity: weatherinfo.main.humidity
    })
  }

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

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