Tag: SPFX

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

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