SPFx Application Customizer - An Analog Clock With REACT

In this article, you will learn about SPFx application customizer. We will add an analog clock with REACT in our app.

Introduction

 
In this article, we will explore how to show the React Analog Clock in SharePoint Framework. We will use the Application Customizer extension to show an analog clock in header placeholder.
 

Create an extension project

  • Run Windows PowerShell as administrator.
  • Create a new project directory named “ReactAnalogExt” in your preferred location using the below command.
  • md ReactAnalogExt
  • cd ReactAnalogExt
  • Create a new AppCustomizer extension by running the below command in the console.
  • yo @microsoft/sharepoint

Provide required information when prompted

  • Keep the default react-analog-ext for “What is your solution name?” and select "Enter".
  • Keep SharePoint Online only (latest) for “Which baseline packages do you want to target for your component(s)?” and select Enter.
  • Keep Use the current folder for “Where do you want to place the files?” and select Enter.
  • Select No (N) to require tenant admin install extension on each site and press Enter. Here, make sure you select No (N). If you choose Yes (y), Elements.xml feature deployment file will not be generated through scaffolding.
  • Choose Extension for “Which type of client-side component to create?” (Use arrow keys)
  • Select Application Customizer as extension type from the list of available options.
As soon as you select Application Customizer, next, the group of prompts asks for information regarding your extension.
  • Add ReactAnalog as your extension name, and press Enter.
  • Keep the default ReactAnalogdescription for “What is your Application Customizer description?” and select Enter.
SPFx Application Customizer - An Analog Clock With REACT 
 
Yeoman installs the needed dependencies and scaffolds the solution files along with the AppCustomizer extension. This may take some time to install the dependencies files.
 
When scaffolding is done, you will get a successful scaffold message. After a successful scaffold, the below message appears.
 
SPFx Application Customizer - An Analog Clock With REACT 
 
To start, open the solution in Visual Studio Code and type the following command.
 
Code .
 

React-analog Clock(npm Packages)

 
Add React-Clock to Application Customizer extension. The below points are required.
  • Install by executing npm install react-clock
  • Import by adding import Clock from 'react-clock'.
  • Use by adding <Clock />. 

Structure of the solution for Application Customizer

 
SPFx Application Customizer - An Analog Clock With REACT
  • Debug Application Customizer
    Local Workbench cannot be used to test SharePoint Framework Extensions. You can test the extension using the SharePoint Online site. However, you do not need to deploy your customization to the site.

  • Open up JSON file from inside the config folder. you will need to edit this file for debugging purpose. Edit pageURL (Current siteURL) for your tenant, which you need to utilize for testing purpose.

    SPFx Application Customizer - An Analog Clock With REACT

  • serve.json
    1. "$schema""https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",  
    2.   "port": 4321,  
    3. "https"true,  
    4.  "serveConfigurations": {  
    5.   "default": {  
    6.       "pageUrl""https://Domain-name/sites/Demo/SitePages/Home.aspx",  
    7.       "customActions": {  
    8.         "99481ef9-1a6b-492c-88e7-fc8831e81fc1": {  
    9.           "location""ClientSideExtension.ApplicationCustomizer",  
    10.           "properties": {  
    11.             "testMessage""Test message"  
    12.           }  
    13.         }  
    14.       }  
    15.     },  
    16.     "reactAnalog": {  
    17.       "pageUrl""https:// Domain-name/sites/Demo/SitePages/Home.aspx",  
    18.       "customActions": {  
    19.         "99481ef9-1a6b-492c-88e7-fc8831e81fc1": {  
    20.           "location""ClientSideExtension.ApplicationCustomizer",  
    21.           "properties": {  
    22.             "testMessage""Test message"  
    23.           }  
    24.         }  
    25.       }  
    26.     }  
    27.   }  
    28. }  

Implement the Application Customizer

  • Application Customizer extensions are supported with Site, Web, and List
  • Open the ReactAnalogApplicationCustomizer.ts file in the src\extensions\reactAnalog\ReactAnalogApplicationCustomizer.ts
  • It imports the base class BaseApplicationCustomizer for the App Customizer from sp-application-base package which contains SharePoint framework code.
  • Add the PlaceholderContent and PlaceholderName to the import from @microsoft/sp-application-base by updating the import statement as follows,
    1.  import {  
    2.     BaseApplicationCustomizer,  
    3.     PlaceholderContent,  
    4.     PlaceholderName  
    5. } from '@microsoft/sp-application-base';  
  • Create the React Component for Analog Clock under Extension folder:
  • Create the tsx file under the src\extensions\reactAnalog\
  • In the below code Import reack-clock reference required

    reactAnalog.tsx
    1. import * as React from 'react';  
    2. import Clock from 'react-clock';  
    3. import styles from './AppCustomizer.module.scss';  
    4. export interface IreactAnalogProps {  
    5.      
    6. }  
    7. export interface IreactAnalogPropsoState {  
    8.     currentTime: Date;  
    9. }  
    10. export default class reactAnalog extends React.Component<IreactAnalogProps,IreactAnalogPropsoState> {  
    11.     constructor(props: IreactAnalogProps) {  
    12.         super(props)  
    13.        this.startClock()  
    14.         this.state = {  
    15.          currentTime : new Date()  
    16.       }  
    17.      }  
    18.      startClock() {  
    19.         setInterval(() => {  
    20.          console.log("updating time")  
    21.          this.setState({  
    22.            currentTime: new Date()  
    23.         })  
    24.       }, 1000)  
    25.     }  
    26.   public render(): JSX.Element {  
    27.   return (  
    28.   <div className={styles.topclock}>  
    29.     
    30.    <Clock   
    31.      value={this.state.currentTime}   
    32.  />      
    33.   );  
    34.  }  
    35. }  
  • Branding
    Under the src\extensions\reactAnalog folder, create a new file module.scssas as shown below.

    SPFx Application Customizer - An Analog Clock With REACT
  • Update module.scss with styles used in the HTML output for Analog Clock as well as header.

    AppCustomizer.module.scss
    1. .rectapp{  
    2.   
    3.   .topclock{  
    4.   height0px !important;  
    5.   margin-left:550px!important;  
    6.   margin-top:40px!important;  
    7.   }  
    8.   .topclock time{  
    9.   width96px!important;  
    10.   height92px!important;  
    11.   margin-top-36px!important;  
    12.   margin-bottom563PX!important;  
    13.   }  
    14. }  

ReactAnalogApplicationCustomizer.ts

 
Open src\extensions\appCustomizer\ReactAnalogApplicationCustomizer.ts in the code editor and import at the top, add the below import statements step by step.
 
Steps 1
 
Import React,ReactDOM,PlaceholderContent and PlaceholderName from @microsoft/sp-application-base library.
  1. import { override } from '@microsoft/decorators';  
  2. import { Log } from '@microsoft/sp-core-library';  
  3. import * as React from 'react';  
  4. import * as ReactDOM from "react-dom";   
  5. import {  
  6.   BaseApplicationCustomizer,  
  7.   PlaceholderContent,  
  8.   PlaceholderName  
  9. } from '@microsoft/sp-application-base';  
Steps 2
 
Import the React component by using the below line.
  1. import reactAnalog, { IreactAnalogProps } from './reactAnalog';  
Steps 3 
 
Modify the IReactAnalogApplicationCustomizerProperties interface to add required properties for Header.
  1. export interface IReactAnalogApplicationCustomizerProperties {  
  2.   // This is an example; replace with your own property  
  3.   Top: string;  
  4. }  
Steps 4
 
Add the below private variables. In this case, variables can be defined locally in the onRender method, though if you need to share them with other objects, define the variables as private.
  1. /** A Custom Action which can be run during the execution of a Client-Side Application */  
  2. export default class ReactAnalogApplicationCustomizer  
  3.   extends BaseApplicationCustomizer<IReactAnalogApplicationCustomizerProperties> {  
  4.     private _topPlaceholder: PlaceholderContent | undefined;  
Steps 5
 
Update the onInit method code as below.
  1. @override  
  2.   public onInit(): Promise<void> {  
  3.     Log.info(LOG_SOURCE, `Initialized ${strings.Title}`);  
  4.   
  5.        this.context.placeholderProvider.changedEvent.add(thisthis._renderPlaceHolders);  
  6.     
  7.     return Promise.resolve<void>();  
  8.   }  
Steps 6
 
Create a new _renderPlaceHolders private method with the following code.
  1. private _renderPlaceHolders(): void {  
  2.     console.log("HelloWorldApplicationCustomizer._renderPlaceHolders()");  
  3.     console.log(  
  4.       "Available placeholders: ",  
  5.       this.context.placeholderProvider.placeholderNames  
  6.         .map(name => PlaceholderName[name])  
  7.         .join(", ")  
  8.     );  
  9.     // Handling the top placeholder  
  10.     if (!this._topPlaceholder)   
  11.     {  
  12.       this._topPlaceholder = this.context.placeholderProvider.tryCreateContent(  
  13.         PlaceholderName.Top,  
  14.         { onDispose: this._onDispose }  
  15.       );  
  16.  // The extension should not assume that the expected placeholder is available.  
  17.       if (!this._topPlaceholder)   
  18.       {  
  19.         console.error("The expected placeholder (Top) was not found.");  
  20.         return;  
  21.       }  
  22.       if (this.properties) {  
  23.         let topString: string = this.properties.Top;  
  24.         if (!topString) {  
  25.           topString = "(Top property was not defined.)";  
  26.         }  
  27.           if (this._topPlaceholder.domElement) {  
  28.         const elem: React.ReactElement<IreactAnalogProps> = React.createElement(  
  29.           reactAnalog,{});  
  30.          ReactDOM.render(elem, this._topPlaceholder.domElement);   
  31.         }       
  32.      }  
  33.     }  
  34.   }  
Steps 7
 
Add _onDispose method as shown below after completion of _renderPlaceHolders method. You can output the below console message on the removal of extension from the page.
  1. private _onDispose(): void   
  2.   {  
  3.     console.log('[ReactAnalogApplicationCustomizer._onDispose] Disposed custom top and bottom placeholders.');  
  4.   }  

Now ready to test the customizer in SharePoint Online 

 
Go Open the Visual code ->Terminal Tab->New terminal,
  1. Developer certificate has to be installed ONLY once in your development environment, so you can skip this step if you have already executed that in your environment.

    gulp trust-dev-cert
  1. Compile your code and host the compiled files from your local computer by running the following command,

    gulp serve
To continue loading scripts from localhost, click "Load debug scripts".
 
SPFx Application Customizer - An Analog Clock With REACT
 

Final O/p

 
SPFx Application Customizer - An Analog Clock With REACT