Digital Clock Extension In SPFX

Introduction

 
react-live-clock is an react plugin to show a digital clock. In this article we will leverage this plugin as an extension to make this visible in the entire site.
 

Steps 

 
Open a command prompt and create a directory for the SPFx solution.
 
md spfx-ReactClockExtension
 
Navigate to the above-created directory.
 
cd spfx-ReactClockExtension
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter for the default name (spfx-ReactClockExtension in this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the 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 - same folder.
 
Deployment option
 
Selecting Y will allow the app to be deployed instantly to all sites and be accessible everywhere.
Selected choice - N (install on each site explicitly).
 
Permissions to access web APIs
 
Choose if the components in the solution require permission 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: ReactClockExtension
 
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 the 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 .  
 NPM Packages used:
  1. npm install react react-dom  
  2. npm i react-live-clock 
 in ReactClockExtensionApplicationCustomizer.ts
  1. import { override } from '@microsoft/decorators';  
  2. import {  
  3.   BaseApplicationCustomizer,    
  4.   PlaceholderContent,      
  5.   PlaceholderName  
  6. } from '@microsoft/sp-application-base';  
  7.   
  8. import * as React from "react";    
  9. import * as ReactDOM from "react-dom";    
  10. import ReactHeader ,{IReactHeaderProps} from "./ReactHeader";     
  11. import * as strings from 'ReactClockExtensionApplicationCustomizerStrings';  
  12. export interface IReactClockExtensionApplicationCustomizerProperties {  
  13.   // This is an example; replace with your own property  
  14.   testMessage: string;  
  15.   Top: string;  
  16. }  
  17.   
  18. /** A Custom Action which can be run during execution of a Client Side Application */  
  19. export default class ReactClockExtensionApplicationCustomizer  
  20.   extends BaseApplicationCustomizer<IReactClockExtensionApplicationCustomizerProperties> {  
  21.     private _topplaceholder: PlaceholderContent | undefined;    
  22.   @override  
  23.   public onInit(): Promise<void> {  
  24.      
  25.     
  26.     // Added to handle possible changes on the existence of placeholders.    
  27.     this.context.placeholderProvider.changedEvent.add(thisthis._renderPlaceHolders);    
  28.         
  29.     // Call render method for generating the HTML elements.    
  30.     this._renderPlaceHolders();    
  31.     
  32.     return Promise.resolve();   
  33.   }  
  34.   private _renderPlaceHolders(): void {    
  35.     console.log('Available placeholders: ',    
  36.     this.context.placeholderProvider.placeholderNames.map(name => PlaceholderName[name]).join(', '));    
  37.          
  38.     // Handling the bottom placeholder    
  39.     if (!this._topplaceholder) {    
  40.       this._topplaceholder =    
  41.         this.context.placeholderProvider.tryCreateContent(    
  42.           PlaceholderName.Top,    
  43.           { onDispose: this._onDispose });    
  44.         
  45.       // The extension should not assume that the expected placeholder is available.    
  46.       if (!this._topplaceholder) {    
  47.         console.error('The expected placeholder (Top) was not found.');    
  48.         return;    
  49.       }    
  50.     
  51.       const elem: React.ReactElement<IReactHeaderProps> = React.createElement(ReactHeader);    
  52.       ReactDOM.render(elem, this._topplaceholder.domElement);        
  53.     }    
  54.   }   
  55.   private _onDispose(): void {    
  56.     console.log('[ReactHeaderFooterApplicationCustomizer._onDispose] Disposed custom top and bottom placeholders.');    
  57. }   

 in mystyle.css
  1. /* latin */  
  2. @font-face {  
  3.     font-family: 'Orbitron';  
  4.     font-style: normal;  
  5.     font-weight: 400;  
  6.     src: url(https://fonts.gstatic.com/s/orbitron/v15/yMJMMIlzdpvBhQQL_SC3X9yhF25-T1nyGy6BoWgz.woff2) format('woff2');  
  7.     unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;  
  8.   }  
  9. .myclock {  
  10.     font-family: 'Orbitron', sans-serif;  
  11.     color: #ff6666;  
  12.     font-size: 56px;  
  13.     text-align: center;  
  14.     padding-top: 40px;  
  15.     padding-bottom: 40px;  
  16.   
  17.   }  
  18.  
  19.   #clockdiv{  
  20.     text-align:center!important;  
  21.   }  
  22.   
 in ReactHeader.tsx
  1. import * as React from "react";    
  2. import Clock from 'react-live-clock';  
  3.  import './mystyle.css';  
  4. export interface IReactHeaderProps {}    
  5. import { SPComponentLoader } from '@microsoft/sp-loader';   
  6.   
  7. export default class ReactHeader extends React.Component<IReactHeaderProps> {    
  8.   constructor(props: IReactHeaderProps) {    
  9.     super(props);    
  10.   }    
  11.     
  12.   public render(): JSX.Element {    
  13.     return (    
  14.       <div id="clockdiv">    
  15.               
  16.            <h1><Clock format={'hh:mm:ssa'} ticking={true} timezone={'Asia/Kolkata'} className="myclock"/></h1>  
  17.                
  18.       </div>    
  19.     );    
  20.   }  } 
Properties
 
Properties Type Default Value Description
date timestamp or string current date Date to output, If nothing is set then it take current date.
format string 'HH:MM' Formatting from moment.js library.
filter function (date: String) => date Filtering the value before the output .
timezone string null If timezone is set, the date is show in this timezone. You can find the list. here, the TZ column.
ticking boolean FALSE If you want the clock to be auto-updated every interval seconds.
interval integer 1000 Auto-updating period for the clock. 1 second is a default value.
className string null Extra class.
children string null date can be set as a children prop.
onChange function ({output, previousOutput, moment}) => {} callback function on each output update
 

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.     "reactClockExtension": {  
  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”.
 
Expected output
 
Digital Clock Extension In SPFX
 

Conclusion

 
Hence we learned how to implement digital clock in spfx. I hope this helps someone. Happy coding :)