Sample SPFx webpart built using React, also illustrating different scenarios to fetch data from SP REST, PnP, MS Graph and Mockup data.
This webpart illustrates the following concepts on top of the SharePoint Framework:
- Using React for building SharePoint Framework client-side webparts
- Using Office UI Fabric React styles for building user experience consistent with SharePoint and Office
- Communicating with the Microsoft Graph, SharePoint REST API and PnP API
- Passing webpart properties to React components
- Using Chart.js plugin to display chart indicators
git clone the repo
npm i
npm i -g gulp
gulp
This package produces the following:
- lib/* - intermediate-stage commonjs build artifacts
- dist/* - the bundled script, along with other resources
- deploy/* - all resources which should be uploaded to a CDN.
-
gulp trust-dev-cert
Command to install the developer certificate for building your custom solutions easily with HTTPS endpoint.
-
gulp clean
Command to clear the temporary build folders and files created in the solution. Some of the folders cleaned up during the process are
temp/
anddist/
. -
gulp serve
This command executes a series of gulp tasks to create a local, node-based HTTPS server on
localhost:4321
and launches your default browser to preview webparts from your local dev environment. Note: if you see issues with the certificate in the browser, please rungulp trust-dev-cert
command. The minified assets can be found under thetemp\deploy
directory. -
gulp bundle
Command to build a bundle of your solution.
-
gulp bundle --ship
This builds the minified assets required to upload to the CDN provider. The
--ship
indicates the build tool to build for distribution. -
gulp package-solution
This command packages one or more client-side component manifests, such as webparts, along with the feature XML files referenced in the
package-solution.json
configuration file. -
gulp package-solution --ship
Same as the previous command but with
--ship
flag to package minified versions of your components. -
gulp serve --locale=es-es
To specify the locale to be used by the local SharePoint workbench. More info
- Install TSLint extension on VSCode
- Add a
tslint.json
file on the root of the project to tell the extension to get its rules from theconfig
folder:{ rulesDirectory: './config' }
-
Install Prettier extension:
ext install prettier-vscode
-
Add a
.prettierrc
file to the root of the project to tell the extension to use the following prettier rules:{ singleQuote: true }
NOTE: To avoid rule conflicts between TSLint and Prettier follow below steps.
-
Install some packages and update TSLint rules:
npm install --save-dev tslint tslint-config-prettier tslint-eslint-rules tslint-react
- Update
./config/tslint.json
file to extend the default linting functionality:
"lintConfig": { "extends": [ "tslint:latest", "tslint-react", "tslint-eslint-rules", "tslint-config-prettier" ], "rules": { // ... other rules omitted for brevity "quotemark": [true, "single", "jsx-double"] } }
- Install packages:
npm install --save-dev husky lint-staged prettier
- Edit the
package.json
file to configure the git hooks as following:
"scripts": { // ... other scripts omitted for brevity
"precommit": "lint-staged",
},
"lint-staged": {
"*.{json,css,scss,md}": [
"prettier --write",
"git add"
],
"*.{js,ts,tsx}": [
"tslint --fix",
"prettier --single-quote --parser typescript --write",
"git add"
]
},
- Now, every time
git commit
command is executed, the staged files will be formatted according to tslint and prettier rules configured.
On src/EmployeePerformanceAppWebPart.manifest.json
file, update following properties:
- Group GUID for modern experience:
"groupId": "1bc7927e-4a5e-4520-b540-71305c79c20a", // GUID for Planning and process
- Group name for classic experience:
"group": {
"default": "[Group-name]",
},
NOTE: This icon only applies to modern sites.
- The easiest way to configure a webpart icon is to use an icon name from Office UI Fabric
- On
src/EmployeePerformanceAppWebPart.manifest.json
file, update following property:
"officeFabricIconFontName": "[icon-name]",
NOTE: This icon only applies to classic sites.
- Get an image icon with 96px to 96px dimension.
- Upload the icon to the
sharepoint/images
folder - On
config/package-solution.json
file, update the following property to reference the new icon:
"iconPath": "images/[icon-name].png",
This sample webpart provide four different lists to a SharePoint site
- Add SP List schemas inside the
sharepoint/assets
folder - Add a "features" option on
config/package-solution.json
file to reference the lists schemas as follows:
"solution": { // other attributes omitted for brevity
"features": [
{
"title": "employee-performance-app-assets",
"description": "List assets for employee performance app",
"id": "368d2b60-be42-4505-986a-5f775c922780",
"version": "1.0.0.0",
"assets": {
"elementManifests": ["elements.xml"],
"elementFiles": [
"employeesListSchema.xml",
"achievementsListSchema.xml",
"earnedAchievementsListSchema.xml",
"performanceSkillsListSchema.xml"
]
}
}
],
}
For more information on how to provision SP assets, please read carefully this guide and these samples: sample 1, sample 2.
- For localization string resources declare the property names of the strings inside the
[webpart]/loc/mystrings.d.ts
file, example:
declare interface IEmployeePerformanceAppWebPartStrings {
PropertyPaneDescription: string;
CardsMenuLabel: string;
InformationMenuLabel: string;
AchievementsMenuLabel: string;
PerformanceMenuLabel: string;
DataProviderGroupName: string;
}
-
Add the resources files inside the
[webpart]/loc
folder using LCID named files. example:en-us.js
: For englishes-es.js
: For spanish
-
To use the string resources import them as following:
import * as strings from 'EmployeePerformanceAppWebPartStrings';
Each folder purpose is described below:
Folder | Purpose |
---|---|
data | To store api calls |
loc | To store localization strings |
models | To store the models of the objects to use on your webpart code |
styles | To store global styles and variables of the SCSS of the webpart |
components | To store all the components that integrate the webpart |
For more recomendations on how to properly scaffold the project, please read this document.
This webpart uses different data providers to fetch data from SharePoint:
Data Provider | Description |
---|---|
Mockup Data | Dummy JSON data to easily test the webpart functionality |
SP REST | Fetch data using SharePoint REST services, more info here |
PnP api | Fetch data using PnP api, more info here |
MS Graph | Fetch data using MS Graph api, more info here, another spfx project using MS Graph here |
This property indicates the environment where the SPFx is running and it is pretty useful if the webpart needs to behave different depending the running environment, it has four types and values:
- 0 = Test
- 1 = Local
- 2 = SharePoint
- 3 = ClassicSharePoint
By default the package template comes with two debug configurations, on for the local workbench and the other onw for the hosted workbench (online).
To debug the code on the local workbench, follow the next steps:
- Add a breakpoint
- Run this command on the terminal:
gulp serve --nobrowser
- Press
F5
to start the debbuging option on VSCode - On the local workbench, add the webpart to the page
To debug the code on the hosted workbench, follow the next steps:
- Update the
url
property on the.vscode/launch.json
file
{
"name": "Hosted workbench",
"type": "chrome",
"request": "launch",
"url": "https://[SharePoint-Site]/_layouts/workbench.aspx",
... // other properties omitted for brevity
}
- Add a breakpoint
- Run this command on the terminal:
gulp serve --nobrowser
- Press
F5
to start the debbuging option on VSCode - On the hosted workbench, add the webpart to the page
This webpart shows how to render a choice property and also to disable the reactive updates form the proerty pane by overriding disableReactivePropertyChanges
method:
// Override this method to disable reactive property pane
protected get disableReactivePropertyChanges(): boolean {
return true;
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.DataProviderGroupName,
groupFields: [
PropertyPaneChoiceGroup('dataProvider', {
options: [
{ key: DataProvider.MockData, text: 'Mock Data' },
{ key: DataProvider.MSGraph, text: 'MS Graph' },
{ key: DataProvider.PnP, text: 'PnP API' },
{ key: DataProvider.REST, text: 'REST Service' }
]
})
]
}
]
}
]
};
}
}
To update the DataProvider of the webpart, while running the webpart open the property pane, select one data provider to fetch the information and finally click on "Apply" button.
For more information regarding property pane configuration go here
- Bundle the project to verify everything will complie properly by running the following command using
--ship
argument to bundle it in production mode:
gulp bundle --ship
- Package the project by running the following command using
--ship
argument to package it in production mode:
gulp package-solution --ship
- Upload the
.ppkg
file to the app catalog on your tenant - Install the app on your site
- Add the webpart to a SharePoint page
THIS CODE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.