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. import * as React from "react";
  8. import * as ReactDOM from "react-dom";
  9. import ReactHeader ,{IReactHeaderProps} from "./ReactHeader";
  10. import * as strings from 'ReactClockExtensionApplicationCustomizerStrings';
  11. export interface IReactClockExtensionApplicationCustomizerProperties {
  12. // This is an example; replace with your own property
  13. testMessage: string;
  14. Top: string;
  15. }
  16. /** A Custom Action which can be run during execution of a Client Side Application */
  17. export default class ReactClockExtensionApplicationCustomizer
  18. extends BaseApplicationCustomizer<IReactClockExtensionApplicationCustomizerProperties> {
  19. private _topplaceholder: PlaceholderContent | undefined;
  20. @override
  21. public onInit(): Promise<void> {
  22. // Added to handle possible changes on the existence of placeholders.
  23. this.context.placeholderProvider.changedEvent.add(this, this._renderPlaceHolders);
  24. // Call render method for generating the HTML elements.
  25. this._renderPlaceHolders();
  26. return Promise.resolve();
  27. }
  28. private _renderPlaceHolders(): void {
  29. console.log('Available placeholders: ',
  30. this.context.placeholderProvider.placeholderNames.map(name => PlaceholderName[name]).join(', '));
  31. // Handling the bottom placeholder
  32. if (!this._topplaceholder) {
  33. this._topplaceholder =
  34. this.context.placeholderProvider.tryCreateContent(
  35. PlaceholderName.Top,
  36. { onDispose: this._onDispose });
  37. // The extension should not assume that the expected placeholder is available.
  38. if (!this._topplaceholder) {
  39. console.error('The expected placeholder (Top) was not found.');
  40. return;
  41. }
  42. const elem: React.ReactElement<IReactHeaderProps> = React.createElement(ReactHeader);
  43. ReactDOM.render(elem, this._topplaceholder.domElement);
  44. }
  45. }
  46. private _onDispose(): void {
  47. console.log('[ReactHeaderFooterApplicationCustomizer._onDispose] Disposed custom top and bottom placeholders.');
  48. }
  49. }
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. #clockdiv{
  18. text-align:center!important;
  19. }

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. export default class ReactHeader extends React.Component<IReactHeaderProps> {
  7. constructor(props: IReactHeaderProps) {
  8. super(props);
  9. }
  10. public render(): JSX.Element {
  11. return (
  12. <div id="clockdiv">
  13. <h1><Clock format={'hh:mm:ssa'} ticking={true} timezone={'Asia/Kolkata'} className="myclock"/></h1>
  14. </div>
  15. );
  16. } }
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 :)