Create Extension With SharePoint Framework(SPFx)

Introduction

In this article, we will learn to create an extension using SharePoint Framework. In the previous article, we have already learned the basic information about the SPFx Extension(click here). To start development with SPFx extensions we need a setup development environment that we have already learned in the previous article(click here).

What are Extension and their types

Using SPFx Extensions we can customize other parts of the SharePoint like the Notification area, Header, Footer, toolbars, and list views. Extensions can not run in a Classic environment. SPFx Extensions can extend the SharePoint user experience to Modern SharePoint Pages, Lists, and Document libraries using SPFX tools and libraries for client-side development.

Types of SPFx Extensions,

  • Application Customizer
  • Field Customizer
  • List view command set

Create Application Customizer Extension

Let’s create a new SPFx extension to render a custom Header on SharePoint Modern UI. To create a Header Extension we need to create an Application customizer because the application customizer loads on the initial load of the SharePoint Modern pages and render UI section on some particular section like Header, Footer, or HTML div section. So let’s follow the below instructions to create a Header Extension to render a custom Header.

Here we have created one folder with the name FirstSPFxExtension in the D:/Solutions location.

Create Extension with SharePoint Framework(SPFx)

Open Visual Studio Code and open the folder D:\Solutions\FirstSPFxExtension location in Visual Studio Code.

Create Extension with SharePoint Framework(SPFx)

Open Node Terminal inside Visual Studio Code.

Create Extension with SharePoint Framework(SPFx)

Node Terminal will open at the bottom of the window.

Create Extension with SharePoint Framework(SPFx)

Run the below command in the terminal to create a new solution on the current location.

yo @microsoft/sharepoint

SharePoint Generator will run and ask for user input like Solution name, Target environment(SharePoint Online only (latest)/SharePoint 2016 onwards, including 2019 and SharePoint Online SharePoint 2019 onwards, including SharePoint Online), file placement, tenant deployment feature, and permission requirement for web APIs. Below we have answered all these user inputs from the SharePoint generator.

Create Extension with SharePoint Framework(SPFx)

After that generator will ask for one important user input which is the component type. We can create a Web part, extension, or library using SPFx so we need to choose from this option because the functionality of all three solutions will be different.

Create Extension with SharePoint Framework(SPFx)

After selecting the solution type as Extension, there will be another option to ask the Extension type that we want to create. Here we will select Application Customizer because we are going to add a custom Header using this extension.

Create Extension with SharePoint Framework(SPFx)

After selecting the extension type generator will ask to name the extension name and its description. After entering the details SharePoint generator will start generating solutions according to our selected options and we can see the generated files in the file explorer.

Create Extension with SharePoint Framework(SPFx)

Create Extension with SharePoint Framework(SPFx)

Here we will render our header using react component. So let’s create one react component file. We have created the Header.tsx file in src > extensions > firstSPFxExtension folder to generate the header component. Add the below code which renders static header data using Fluent UI command bar.

import * as React from "react";
import { CommandBar, ICommandBarItemProps } from 'office-ui-fabric-react';

const _items: ICommandBarItemProps[] = [
  {
    key: 'Home',
    text: 'Home',
    iconProps: { iconName: 'Home' },
    subMenuProps: {
      items: [
        { key: 'Site1', text: 'Site1' },
        { key: 'Site2', text: 'Site 2' },
      ],
    },
  },
  {
    key: 'Office',
    text: 'Office',
    iconProps: { iconName: 'OfficeLogo' },
    href: 'https://Office.com',
  },
  { key: 'Share', text: 'Share', iconProps: { iconName: 'Share' }, onClick: () => console.log('Share') },
  { key: 'Download', text: 'Download', iconProps: { iconName: 'Download' }, onClick: () => console.log('Download') },
];
export class Header extends React.Component<{}, {}> {

  /**
   * Main React Render fuction
   */
  public render(): JSX.Element {
    return (
      <div>
        <CommandBar
          items={_items}
        />
      </div>
    );
  }
}

After creating the header component we need to bind it to the particular div section. As we are creating a Header for the SharePoint site so we need to render it on Top placeholder of the site. We can see FirstSpFxExtensionApplicationCustomizer.ts file on src > extensions > firstSPFxExtension folder path. Which is the trigger file of the solution and load first with the extension. So we need to bind our header to react components within this file. First, we need to import the below modules. Our created header component on the top of the FirstSpFxExtensionApplicationCustomizer.ts file.

import * as React from "react";
import * as ReactDOM from "react-dom";
import {
  BaseApplicationCustomizer,
  PlaceholderContent,
  PlaceholderName
} from '@microsoft/sp-application-base';
import { Header } from "./Header";

After importing the required modules we will find the onInit() function where we can see some already defined code that loads the success message dialog box after loading the extension successfully but we need to remove all code except the return statement of the function and place the code to render our Header module on the top placeholder so the onInit() function will look like below after updating the code.

@override
  public onInit(): Promise<void> {
    const headerData: PlaceholderContent = this.context.placeholderProvider.tryCreateContent(PlaceholderName.Top, {});

    if (!headerData) {
      Log.error(LOG_SOURCE, new Error("Could not find Form PageHeader"));
      return;
    }
    const elem: React.ReactElement<{}> = React.createElement(Header, {});
    ReactDOM.render(elem, headerData.domElement);
    return Promise.resolve();
  }

Run Application Customizer Extension

As we have completed the code which will render the header component on the top placeholder. Now we can test it by running the extension on the local server and try to load on the actual site.

But first, we need to change the default serve URL which loads the welcome site when we run the extension on the local server. For that, we need to change the pageUrl property with our actual site in the serve.json file in the config folder.

Create Extension with SharePoint Framework(SPFx)

Now run the below command in the node terminal to start the server.

 gulp serve

After running the command site, the URL that we have given in the serve.json file will load in the default browser with some extension URL parameters. A confirmation dialog will be displayed to get user approval to load the extension on the site. So we can select the Load debug scripts option from a dialog box.

Create Extension with SharePoint Framework(SPFx)

Header extension will be loaded on the top div and looks like below,

Create Extension with SharePoint Framework(SPFx)

After confirming the header look we want on the local server we can publish and deploy it on the actual site by using the same steps we have followed to deploy the SPFx web part here.

Conclusion

In this article, we learned to create the SPFx Header extension using the Fluent UI command bar. Also, we learn how we can test it on a local server. If you find anything that I am missing in this article or you find it useful please provide your valuable feedback.