New Sample: Consuming SPFX Service Scopes using React Hooks
This commit is contained in:
parent
0868acab74
commit
72541ea7ad
|
@ -0,0 +1,66 @@
|
|||
# Consuming SPFX Service Scopes using React Hooks
|
||||
|
||||
## Summary
|
||||
|
||||
This web part is designed to help developers understand how to use the Context API and useContext() React Hook to share global data between a hierarchy of nested React components. In this example, a Service Scope is shared globally that components can consume to call the Microsoft Graph, it also uses Functional Components replacing the more commonly seen Class Component approach.
|
||||
|
||||
![webpart](webpart.png)
|
||||
|
||||
## Used SharePoint Framework Version
|
||||
|
||||
![drop](https://img.shields.io/badge/version-1.10.0-green.svg)
|
||||
|
||||
## Applies to
|
||||
|
||||
* [SharePoint Framework](https:/dev.office.com/sharepoint)
|
||||
* [Office 365 tenant](https://dev.office.com/sharepoint/docs/spfx/set-up-your-development-environment)
|
||||
|
||||
## Solution
|
||||
|
||||
Solution|Author(s)
|
||||
--------|---------
|
||||
react-functional-servicescope-hooks | Garry Trinder
|
||||
|
||||
## Version history
|
||||
|
||||
Version|Date|Comments
|
||||
-------|----|--------
|
||||
1.0|March 25, 2020|Initial release
|
||||
|
||||
## Disclaimer
|
||||
|
||||
**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.**
|
||||
|
||||
---
|
||||
|
||||
## Minimal Path to Awesome
|
||||
|
||||
* Clone this repository
|
||||
* Move to /samples/react-functional-servicescope-hooks folder
|
||||
* At the command line run:
|
||||
* `npm install`
|
||||
* `gulp bundle --ship && gulp package-solution --ship`
|
||||
* Upload `react-functional-servicescope-hooks.sppkg` to App Catalog site collection from `sharepoint/solution` folder
|
||||
* Deploy package
|
||||
* Go to SharePoint API Management screen in SharePoint Admin Center
|
||||
* Approve `User.ReadBasic.All` permission for Microsoft Graph
|
||||
* At the command line run:
|
||||
* `gulp serve`
|
||||
* Navigate to remote workbench `https://tenant.sharepoint.com/_layouts/15/workbench.aspx`
|
||||
* Add `HelloWorld` web part to workbench
|
||||
|
||||
## Features
|
||||
|
||||
This sample demonstrates how
|
||||
|
||||
* Functional Components can be used to replace Class Components, simplifying the codebase
|
||||
* `useEffect()` React Hooks can replace `componentDidMount()` lifecycle method
|
||||
* `useState()` React Hook can replace the use of `this.setState()` to update local component state
|
||||
|
||||
This Web Part illustrates the following concepts on top of the SharePoint Framework:
|
||||
|
||||
* React Hooks
|
||||
* React Context API
|
||||
* Functional Components
|
||||
|
||||
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/readme-template" />
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
|
||||
"version": "2.0",
|
||||
"bundles": {
|
||||
"hello-world-web-part": {
|
||||
"components": [
|
||||
{
|
||||
"entrypoint": "./lib/webparts/helloWorld/HelloWorldWebPart.js",
|
||||
"manifest": "./src/webparts/helloWorld/HelloWorldWebPart.manifest.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"externals": {},
|
||||
"localizedResources": {
|
||||
"HelloWorldWebPartStrings": "lib/webparts/helloWorld/loc/{locale}.js"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/copy-assets.schema.json",
|
||||
"deployCdnPath": "temp/deploy"
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
|
||||
"workingDir": "./temp/deploy/",
|
||||
"account": "<!-- STORAGE ACCOUNT NAME -->",
|
||||
"container": "react-functional-servicescope-hooks",
|
||||
"accessKey": "<!-- ACCESS KEY -->"
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
|
||||
"solution": {
|
||||
"name": "react-functional-servicescope-hooks",
|
||||
"id": "d3c47cd9-9bbd-49f1-a8ef-9aa2260a6257",
|
||||
"version": "1.0.0.0",
|
||||
"includeClientSideAssets": true,
|
||||
"skipFeatureDeployment": true,
|
||||
"webApiPermissionRequests": [
|
||||
{
|
||||
"resource": "Microsoft Graph",
|
||||
"scope": "User.ReadBasic.All"
|
||||
}
|
||||
]
|
||||
},
|
||||
"paths": {
|
||||
"zippedPackage": "solution/react-functional-servicescope-hooks.sppkg"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
|
||||
"port": 4321,
|
||||
"https": true,
|
||||
"initialPage": "https://localhost:5432/workbench",
|
||||
"api": {
|
||||
"port": 5432,
|
||||
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
|
||||
"cdnBasePath": "<!-- PATH TO CDN -->"
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
const build = require('@microsoft/sp-build-web');
|
||||
|
||||
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
|
||||
|
||||
build.initialize(require('gulp'));
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,42 @@
|
|||
{
|
||||
"name": "spfx-servicescope-hooks",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"main": "lib/index.js",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "gulp bundle",
|
||||
"clean": "gulp clean",
|
||||
"test": "gulp test"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "16.8.5",
|
||||
"react-dom": "16.8.5",
|
||||
"@types/react": "16.8.8",
|
||||
"@types/react-dom": "16.8.3",
|
||||
"office-ui-fabric-react": "6.189.2",
|
||||
"@microsoft/sp-core-library": "1.10.0",
|
||||
"@microsoft/sp-property-pane": "1.10.0",
|
||||
"@microsoft/sp-webpart-base": "1.10.0",
|
||||
"@microsoft/sp-lodash-subset": "1.10.0",
|
||||
"@microsoft/sp-office-ui-fabric-core": "1.10.0",
|
||||
"@types/webpack-env": "1.13.1",
|
||||
"@types/es6-promise": "0.0.33"
|
||||
},
|
||||
"resolutions": {
|
||||
"@types/react": "16.8.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@microsoft/sp-build-web": "1.10.0",
|
||||
"@microsoft/sp-tslint-rules": "1.10.0",
|
||||
"@microsoft/sp-module-interfaces": "1.10.0",
|
||||
"@microsoft/sp-webpart-workbench": "1.10.0",
|
||||
"@microsoft/rush-stack-compiler-3.3": "0.3.5",
|
||||
"gulp": "~3.9.1",
|
||||
"@types/chai": "3.4.34",
|
||||
"@types/mocha": "2.2.38",
|
||||
"ajv": "~5.2.2"
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
// A file is required to be in the root of the /src directory by the TypeScript compiler
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
|
||||
"id": "216d3c26-ed6d-4402-ba29-1e7ae3a121bc",
|
||||
"alias": "HelloWorldWebPart",
|
||||
"componentType": "WebPart",
|
||||
|
||||
// The "*" signifies that the version should be taken from the package.json
|
||||
"version": "*",
|
||||
"manifestVersion": 2,
|
||||
|
||||
// If true, the component can only be installed on sites where Custom Script is allowed.
|
||||
// Components that allow authors to embed arbitrary script code should set this to true.
|
||||
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
|
||||
"requiresCustomScript": false,
|
||||
"supportedHosts": ["SharePointWebPart"],
|
||||
|
||||
"preconfiguredEntries": [{
|
||||
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
|
||||
"group": { "default": "Other" },
|
||||
"title": { "default": "HelloWorld" },
|
||||
"description": { "default": "HelloWorld description" },
|
||||
"officeFabricIconFontName": "Page",
|
||||
"properties": {
|
||||
"description": "HelloWorld"
|
||||
}
|
||||
}]
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
import * as React from 'react';
|
||||
import * as ReactDom from 'react-dom';
|
||||
import { Version } from '@microsoft/sp-core-library';
|
||||
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
|
||||
|
||||
import HelloWorld from './components/HelloWorld';
|
||||
import { IHelloWorldProps } from './components/IHelloWorldProps';
|
||||
|
||||
export interface IHelloWorldWebPartProps {
|
||||
description: string;
|
||||
}
|
||||
|
||||
export default class HelloWorldWebPart extends BaseClientSideWebPart <IHelloWorldWebPartProps> {
|
||||
|
||||
public render(): void {
|
||||
|
||||
const element: React.ReactElement<IHelloWorldProps> = React.createElement(
|
||||
HelloWorld,
|
||||
{
|
||||
description: this.properties.description,
|
||||
serviceScope: this.context.serviceScope //Only need to pass in serviceScope once to the top level component
|
||||
}
|
||||
);
|
||||
|
||||
ReactDom.render(element, this.domElement);
|
||||
}
|
||||
|
||||
protected onDispose(): void {
|
||||
ReactDom.unmountComponentAtNode(this.domElement);
|
||||
}
|
||||
|
||||
protected get dataVersion(): Version {
|
||||
return Version.parse('1.0');
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
import { ServiceScope } from '@microsoft/sp-core-library';
|
||||
import { createContext } from 'react';
|
||||
|
||||
export interface AppContextProps {
|
||||
serviceScope: ServiceScope;
|
||||
}
|
||||
|
||||
// AppContext is created and has an initial value set
|
||||
const AppContext = createContext<AppContextProps>(undefined);
|
||||
|
||||
export default AppContext;
|
|
@ -0,0 +1,45 @@
|
|||
import * as React from 'react';
|
||||
import { MSGraphClientFactory, MSGraphClient } from '@microsoft/sp-http';
|
||||
import { useEffect, useState, useContext } from 'react';
|
||||
import AppContext from '../common/AppContext';
|
||||
|
||||
const HelloUser: React.FunctionComponent = () => {
|
||||
|
||||
/* Sets the initial state value and function to update state */
|
||||
const [name, setName] = useState('');
|
||||
|
||||
/* Returns the serviceScope from the "global" AppContext, which is provided by
|
||||
<AppContext.Provider> component above and is consumed using the useContext React Hook */
|
||||
const { serviceScope } = useContext(AppContext);
|
||||
|
||||
/* Executes once on componentMount */
|
||||
useEffect(() => {
|
||||
|
||||
/* Create a Microsoft Graph client factory using the serviceScope provided by AppContext */
|
||||
const msGraphClientFactory = serviceScope.consume(MSGraphClientFactory.serviceKey);
|
||||
|
||||
/* Create Microsoft Graph Client from factory and call "Me" endpoint */
|
||||
msGraphClientFactory.getClient()
|
||||
.then((client: MSGraphClient): void => {
|
||||
client
|
||||
.api('/me')
|
||||
.get((error, user: any, rawResponse?: any) => {
|
||||
|
||||
/* Update state by calling update function passing the new state value */
|
||||
setName(user.displayName);
|
||||
});
|
||||
});
|
||||
|
||||
}, []);
|
||||
|
||||
/* Display name when state value has been set */
|
||||
return (
|
||||
<div>
|
||||
{name &&
|
||||
<span>Hello {name}</span>
|
||||
}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default HelloUser;
|
|
@ -0,0 +1,74 @@
|
|||
@import '~office-ui-fabric-react/dist/sass/References.scss';
|
||||
|
||||
.helloWorld {
|
||||
.container {
|
||||
max-width: 700px;
|
||||
margin: 0px auto;
|
||||
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.row {
|
||||
@include ms-Grid-row;
|
||||
@include ms-fontColor-white;
|
||||
background-color: $ms-color-themeDark;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.column {
|
||||
@include ms-Grid-col;
|
||||
@include ms-lg10;
|
||||
@include ms-xl8;
|
||||
@include ms-xlPush2;
|
||||
@include ms-lgPush1;
|
||||
}
|
||||
|
||||
.title {
|
||||
@include ms-font-xl;
|
||||
@include ms-fontColor-white;
|
||||
}
|
||||
|
||||
.subTitle {
|
||||
@include ms-font-l;
|
||||
@include ms-fontColor-white;
|
||||
}
|
||||
|
||||
.description {
|
||||
@include ms-font-l;
|
||||
@include ms-fontColor-white;
|
||||
}
|
||||
|
||||
.button {
|
||||
// Our button
|
||||
text-decoration: none;
|
||||
height: 32px;
|
||||
|
||||
// Primary Button
|
||||
min-width: 80px;
|
||||
background-color: $ms-color-themePrimary;
|
||||
border-color: $ms-color-themePrimary;
|
||||
color: $ms-color-white;
|
||||
|
||||
// Basic Button
|
||||
outline: transparent;
|
||||
position: relative;
|
||||
font-family: "Segoe UI WestEuropean","Segoe UI",-apple-system,BlinkMacSystemFont,Roboto,"Helvetica Neue",sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
font-size: $ms-font-size-m;
|
||||
font-weight: $ms-font-weight-regular;
|
||||
border-width: 0;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
display: inline-block;
|
||||
padding: 0 16px;
|
||||
|
||||
.label {
|
||||
font-weight: $ms-font-weight-semibold;
|
||||
font-size: $ms-font-size-m;
|
||||
height: 32px;
|
||||
line-height: 32px;
|
||||
margin: 0 4px;
|
||||
vertical-align: top;
|
||||
display: inline-block;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
import * as React from 'react';
|
||||
import { ServiceScope } from '@microsoft/sp-core-library';
|
||||
import { IHelloWorldProps } from './IHelloWorldProps';
|
||||
import AppContext from '../common/AppContext';
|
||||
import HelloUser from "./HelloUser";
|
||||
|
||||
const HelloWorld: React.FunctionComponent<IHelloWorldProps> = (props: { serviceScope: ServiceScope; }) =>
|
||||
|
||||
/* Context is designed to share data that can be considered “global” for a tree of React components.
|
||||
Set the AppContext value to pass in the serviceScope property which can be consumed by child components */
|
||||
<AppContext.Provider value={{ serviceScope: props.serviceScope }}>
|
||||
|
||||
<h1>Consuming SPFX Service Scopes using React Hooks</h1>
|
||||
<div>
|
||||
<HelloUser />
|
||||
</div>
|
||||
|
||||
</AppContext.Provider>;
|
||||
|
||||
export default HelloWorld;
|
|
@ -0,0 +1,6 @@
|
|||
import { ServiceScope } from '@microsoft/sp-core-library';
|
||||
|
||||
export interface IHelloWorldProps {
|
||||
description: string;
|
||||
serviceScope: ServiceScope;
|
||||
}
|
7
samples/react-functional-servicescope-hooks/src/webparts/helloWorld/loc/en-us.js
vendored
Normal file
7
samples/react-functional-servicescope-hooks/src/webparts/helloWorld/loc/en-us.js
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
define([], function() {
|
||||
return {
|
||||
"PropertyPaneDescription": "Description",
|
||||
"BasicGroupName": "Group Name",
|
||||
"DescriptionFieldLabel": "Description Field"
|
||||
}
|
||||
});
|
10
samples/react-functional-servicescope-hooks/src/webparts/helloWorld/loc/mystrings.d.ts
vendored
Normal file
10
samples/react-functional-servicescope-hooks/src/webparts/helloWorld/loc/mystrings.d.ts
vendored
Normal file
|
@ -0,0 +1,10 @@
|
|||
declare interface IHelloWorldWebPartStrings {
|
||||
PropertyPaneDescription: string;
|
||||
BasicGroupName: string;
|
||||
DescriptionFieldLabel: string;
|
||||
}
|
||||
|
||||
declare module 'HelloWorldWebPartStrings' {
|
||||
const strings: IHelloWorldWebPartStrings;
|
||||
export = strings;
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 3.0 KiB |
Binary file not shown.
After Width: | Height: | Size: 1.4 KiB |
|
@ -0,0 +1,38 @@
|
|||
{
|
||||
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.3/includes/tsconfig-web.json",
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"jsx": "react",
|
||||
"declaration": true,
|
||||
"sourceMap": true,
|
||||
"experimentalDecorators": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "lib",
|
||||
"inlineSources": false,
|
||||
"strictNullChecks": false,
|
||||
"noUnusedLocals": false,
|
||||
"typeRoots": [
|
||||
"./node_modules/@types",
|
||||
"./node_modules/@microsoft"
|
||||
],
|
||||
"types": [
|
||||
"es6-promise",
|
||||
"webpack-env"
|
||||
],
|
||||
"lib": [
|
||||
"es5",
|
||||
"dom",
|
||||
"es2015.collection"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"lib"
|
||||
]
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"extends": "@microsoft/sp-tslint-rules/base-tslint.json",
|
||||
"rules": {
|
||||
"class-name": false,
|
||||
"export-name": false,
|
||||
"forin": false,
|
||||
"label-position": false,
|
||||
"member-access": true,
|
||||
"no-arg": false,
|
||||
"no-console": false,
|
||||
"no-construct": false,
|
||||
"no-duplicate-variable": true,
|
||||
"no-eval": false,
|
||||
"no-function-expression": true,
|
||||
"no-internal-module": true,
|
||||
"no-shadowed-variable": true,
|
||||
"no-switch-case-fall-through": true,
|
||||
"no-unnecessary-semicolons": true,
|
||||
"no-unused-expression": true,
|
||||
"no-use-before-declare": true,
|
||||
"no-with-statement": true,
|
||||
"semicolon": true,
|
||||
"trailing-comma": false,
|
||||
"typedef": false,
|
||||
"typedef-whitespace": false,
|
||||
"use-named-parameter": true,
|
||||
"variable-name": false,
|
||||
"whitespace": false
|
||||
}
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 160 KiB |
Loading…
Reference in New Issue