Using React Components In SPFx Extension Application Customizer

In this article, we will explore the how we can use React components in the Application Customizer part of SharePoint extensions.

Overview

 
SharePoint Framework (SPFx) Extensions extend the SharePoint user experience by customizing predefined placeholders in the SharePoint site. As of today, we can extend the top and bottom placeholders to customize the header and footer section. React components help to develop functionality independently by maintaining separation of concerns. These React components can be used as part of application customizer.
 

Create SPFx Solution

 
Open the command prompt. Create a directory for SPFx solution.
  1. md spfx-react-applicationcustomizer  
Navigate to the above-created directory.
  1. cd spfx-react-applicationcustomizer  
Run the Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint   
Yeoman generator will present you with the wizard by asking questions about the solution to be created.
 
Yeoman generator for SPFx 
 
Solution Name: Hit Enter to have a default name (spfx-react-applicationcustomizer in this case) or type in any other name for your solution.
Selected choice: Hit enter
 
Target for component: Here, we can select the target environment where we are planning to deploy the client web part i.e. SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice: SharePoint Online only (latest)
 
Place of files: We may choose to use the same folder or create a subfolder for our solution.
Selected choice: Use the current folder.
 
Deployment option: Selecting Y will allow the app to deployed instantly to all sites and will be accessible everywhere.
Selected choice: Y
 
Permissions to access web APIs: Choose if the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant.
Selected choice: N (solution contains unique permissions)
 
Type of client-side component to create: We can choose to create client-side webpart or an extension.
Selected choice: Extension
 
Type of client-side extension to create: We can choose to create Application customizer, Field customizer, or ListView Command Set.
Selected choice: Application Customizer
 
Application customizer name: Hit Enter to select the default name or type in any other name.
Selected choice: ReactHeaderFooter
 
Application customizer description: Hit Enter to select the default description or type in any other value.
Selected choice: Adds custom header and footer to a SharePoint site
 
Yeoman generator will perform scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running below command.
  1. npm shrinkwrap  
In the command prompt type the below command to open the solution in code editor of your choice.
  1. code .  
To use Office 365 UI Fabric controls, type below command. We will explicitly install the 5.x version of the Office UI Fabric to our solution.
  1. npm install office-ui-fabric-react@5.132.0 --save  
One thing to note here is that during the solution creation, Yeoman generator did not ask us for the choice of language to use.
 

Implement Application Customizer

 
Open ReactHeaderFooterApplicationCustomizer.ts under “\src\extensions\ reactHeaderFooter \” folder. To get access to placeholders on the page, use below imports.
  1. import {  
  2.   BaseApplicationCustomizer,  
  3.   PlaceholderContent,  
  4.   PlaceholderName  
  5. } from '@microsoft/sp-application-base';  
Update the interface IReactHeaderFooterApplicationCustomizerProperties to include Top and Bottom properties.
  1. export interface IReactHeaderFooterApplicationCustomizerProperties {  
  2.   // This is an example; replace with your own property  
  3.   Bottom: string;  
  4. }  
Implement the OnInit method.
  1. private _bottomPlaceholder: PlaceholderContent | undefined;  
  2.   
  3. public onInit(): Promise<void> {  
  4.     Log.info(LOG_SOURCE, `Initialized ${strings.Title}`);  
  5.   
  6.     // Added to handle possible changes on the existence of placeholders.  
  7.     this.context.placeholderProvider.changedEvent.add(thisthis._renderPlaceHolders);  
  8.       
  9.     // Call render method for generating the HTML elements.  
  10.     this._renderPlaceHolders();  
  11.   
  12.     return Promise.resolve();  
  13.   }  
Implement _renderPlaceHolders method,
  1. private _renderPlaceHolders(): void {  
  2.     console.log('Available placeholders: ',  
  3.     this.context.placeholderProvider.placeholderNames.map(name => PlaceholderName[name]).join(', '));  
  4.        
  5.     // Handling the bottom placeholder  
  6.     if (!this._bottomPlaceholder) {  
  7.       this._bottomPlaceholder =  
  8.         this.context.placeholderProvider.tryCreateContent(  
  9.           PlaceholderName.Bottom,  
  10.           { onDispose: this._onDispose });  
  11.       
  12.       // The extension should not assume that the expected placeholder is available.  
  13.       if (!this._bottomPlaceholder) {  
  14.         console.error('The expected placeholder (Bottom) was not found.');  
  15.         return;  
  16.       }  
  17.     }  
  18.   }  
Use this.context.placeholderProvider.tryCreateContent to get access the placeholder, without assuming that the placeholder will exists.
 
Implement the OnDispose method.
  1. private _onDispose(): void {  
  2.     console.log('[ReactHeaderFooterApplicationCustomizer._onDispose] Disposed custom top and bottom placeholders.');  
  3. }  

Implement React Component as Footer

 
Add a new file to solution – ReactFooter.tsx.
  1. import * as React from "react";  
  2. import { Link } from 'office-ui-fabric-react/lib/Link';  
  3. import { CommandBar } from 'office-ui-fabric-react/lib/CommandBar';  
  4.   
  5. export interface IReactFooterProps {}  
  6.   
  7. export default class ReactFooter extends React.Component<IReactFooterProps> {  
  8.   constructor(props: IReactFooterProps) {  
  9.     super(props);  
  10.   }  
  11.   
  12.   public render(): JSX.Element {  
  13.     return (  
  14.       <div className={"ms-bgColor-themeDark ms-fontColor-white"}>  
  15.         <CommandBar  
  16.           items={this.getItems()}  
  17.         />       
  18.       </div>  
  19.     );  
  20.   }  
  21.   
  22.   // Data for CommandBar  
  23.   private getItems = () => {  
  24.     return [  
  25.       {  
  26.         key: 'microsoft',  
  27.         name: 'Microsoft',  
  28.         cacheKey: 'myCacheKey'// changing this key will invalidate this items cache  
  29.         iconProps: {  
  30.           iconName: 'AzureLogo'  
  31.         },  
  32.         href: 'https://www.Microsoft.com'  
  33.       },  
  34.       {  
  35.         key: 'officeUIFabric',  
  36.         name: 'Office UI Fabric',  
  37.         iconProps: {  
  38.           iconName: 'OneDrive'  
  39.         },  
  40.         href: 'https://dev.office.com/fabric',  
  41.         ['data-automation-id']: 'uploadButton'  
  42.       }  
  43.     ];  
  44.   }  
  45. }  
Open src\extensions\reactHeaderFooter\ReactHeaderFooterApplicationCustomizer.ts. Add below imports.
  1. import * as React from "react";  
  2. import * as ReactDOM from "react-dom";  
  3. import ReactFooter, { IReactFooterProps } from "./ReactFooter";  
Update _renderPlaceHolders method to include our React component.
  1. private _renderPlaceHolders(): void {  
  2.     console.log('Available placeholders: ',  
  3.     this.context.placeholderProvider.placeholderNames.map(name => PlaceholderName[name]).join(', '));  
  4.        
  5.     // Handling the bottom placeholder  
  6.     if (!this._bottomPlaceholder) {  
  7.       this._bottomPlaceholder =  
  8.         this.context.placeholderProvider.tryCreateContent(  
  9.           PlaceholderName.Bottom,  
  10.           { onDispose: this._onDispose });  
  11.       
  12.       // The extension should not assume that the expected placeholder is available.  
  13.       if (!this._bottomPlaceholder) {  
  14.         console.error('The expected placeholder (Bottom) was not found.');  
  15.         return;  
  16.       }  
  17.   
  18.       const elem: React.ReactElement<IReactFooterProps> = React.createElement(ReactFooter);  
  19.       ReactDOM.render(elem, this._bottomPlaceholder.domElement);      
  20.     }  
  21.   }  

Test the extension

 
Open serve.json under config folder.
 
Update the properties section to include page URL to test.
  1. {  
  2.   "$schema""https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",  
  3.   "port": 4321,  
  4.   "https"true,  
  5.   "serveConfigurations": {  
  6.     "default": {  
  7.       "pageUrl""https://contoso.sharepoint.com/sites/mySite/SitePages/myPage.aspx",  
  8.       "customActions": {  
  9.         "c633afef-a94d-4970-89ca-30f403612550": {  
  10.           "location""ClientSideExtension.ApplicationCustomizer",  
  11.           "properties": {  
  12.             "testMessage""Test message"  
  13.           }  
  14.         }  
  15.       }  
  16.     },  
  17.     "reactHeaderFooter": {  
  18.       "pageUrl""https://contoso.sharepoint.com/sites/mySite/SitePages/myPage.aspx",  
  19.       "customActions": {  
  20.         "c633afef-a94d-4970-89ca-30f403612550": {  
  21.           "location""ClientSideExtension.ApplicationCustomizer",  
  22.           "properties": {  
  23.             "testMessage""Test message"  
  24.           }  
  25.         }  
  26.       }  
  27.     }  
  28.   }  
  29. }  
On the command prompt, type the below command.
  1. gulp serve  
The SharePoint site will open. Click “Load debug scripts”.
 
Allow debug scripts
 
Observe the footer on the page.
 
React Footer
 

Summary

 
Application customizer SharePoint Framework extension helps to extend the predefined placeholders on Modern SharePoint pages. React components help to develop functionality independently by maintaining separation of concerns. These React components can be used as part of the application customizer.