Getting Started With SharePoint Framework Using PnP JS Library

SharePoint Framework is a new development model that eases the developer's life for developing and testing the application in automated ways when compared to other development models. It also enriches the user’s UI experience in SharePoint sites.

Given below are some references for developing the SharePoint framework applications:

Introduction to SharePoint Framework Development This link contains the summarization of the tools required for developing framework model web part, development prequisites, and how to create a project.

Tutorials and Walkthroughs This contains the below tutorial links to the starting point for SharePoint Framework development.

In this article, we will create a HelloWorld Web Part to talk to SharePoint, by using PnP JavaScript Library (PnP JS version of Tutorial 2: HelloWorld Web Part, Talking to SharePoint).

Before creating a SharePoint Framework solution, we have to ensure the below items for development.

  • The environment should be in Office 365 developer tenant. Due to the current release, it is in initial preview stage.
  • SharePoint site should be a developer site collection.
  • Node JS and npm JS tools.
  • Yeoman and Gulp should be installed globally.
  • Yeoman SharePoint Generator should be installed globally.
  • Upload the workbench.aspx file to Documents Library in a developer site collection.

Create a new SharePoint Framework project

  1. Open any command line tool. I prefer to use Cmder.
  2. Navigate to a folder or create a new folder.
  3. Run the Yeoman Generator to create SharePoint Framework solution package.
  4. Fill the details required for creating a new SharePoint solution.

    details

    • After getting the Success message, we can also run “gulp serve” command to host the application and start the local workbench. The local workbench enables us to test the application in many ways.

      We can also launch the workbench.aspx file from the SharePoint site to test the application in SharePoint Framework.

    • To include the PnP JS library to the project, run the following npm command

      npm i sp-pnp-js –save-dev


      command

    • The command will include the PnP JS file and its dependencies to the project folder.

      command

Now, we have created the solution structure and with dependencies. Next, we will see on updating the code in the generated project to retrieve the list information and render with custom styles.

Updating the Code

The below steps and code snippets are used to populate the visible lists in SharePoint Framework from the SharePoint site.

  • Navigate to solution folder.
  • Define List Model.
  • Style the DOM structure.
  • Retrieve the mockup information for local workbench.
  • Retrieve the actual information from SharePoint site.
  • Render the data based on the environment type (Local / SharePoint).

Navigate to solution folder

  • Open the solution folder in source code editor. I’ll prefer to use Visual Studio Code because it is light weight and available across platforms.

    solution folder

  • Expand src > webparts > PnPjsHelloWorld folder and then select PnPjsHelloWorldWebPart.ts file to edit the code.

    PnPjsHelloWorld

Define List Model

  • Define the interface for the List Model in the code. To define that, open PnPjsHelloWorldWebPart.ts file.
  • Paste the following interface code just below the PnPJsHelloWorldWebPart class.
    1. export interface ISPList {  
    2.     Title: string;  
    3.     Id: string;  
    4. }  
    The ISPList interface holds the SharePoint lists title and id information.

Style DOM structure

SharePoint uses the SaaS language for stylesheets generation. SaaS extends CSS language and allows you to use features, like variables, nested rules, inline imports in the organized way and create efficient style sheets for your web parts.

The SharePoint Framework already comes with a SCSS compiler that converts your Sass files to normal CSS files and also provides a typed version to use it during the development.

Follow these steps to add styles to the entire list collection and particlular list row.

  • Open PnPjsHelloWorld.Module.scss file.
  • Add the following styles below the .button style.
    1. .list  
    2. {  
    3.     color#333333;  
    4. font-family'Segoe UI Regular WestEuropean''Segoe UI'TahomaArialsans-serif;  
    5. font-size14px;  
    6. font-weightnormal;  
    7. box-sizing: border-box;  
    8. margin10;  
    9. padding10;  
    10. line-height50px;  
    11. list-style-typenone;  
    12. box-shadow: 0 4px 4px 0 rgba(0000.2), 0 25px 50px 0 rgba(0000.1);  
    13. }  
    14.   
    15. .listItem   
    16. {  
    17. color: # 333333;  
    18.     vertical - align: center;  
    19.     font - family: 'Segoe UI Regular WestEuropean',  
    20.     'Segoe UI',  
    21.     Tahoma,  
    22.     Arial,  
    23.     sans - serif;  
    24.     font - size14 px;  
    25.     font - weight: normal;  
    26.     box - sizing: border - box;  
    27.     margin0;  
    28.     padding0;  
    29.     box - shadow: none; * zoom: 1;  
    30.     padding9 px 28 px 3 px;  
    31.     positionrelative;  
    32. }  
  • Save the file.

    After running the gulp build or run tasks, the styles from .scss file are converted to the .css file and generate the corresponding typings in .scss.ts file. So, we can import the styles and use them as reference in other typescript files.

    To import the styles in the web part file, add the below line (Auto generated).

    import styles from './PnPjsHelloWorld.module.scss';

    By using the below syntax, we can add style references to the typescript files,

    ${styles.<style name>}

Retrieve List info (mock data) from local environment

We have to ensure the local workbench to display some data in the web part to simulate as same as in SharePoint site. For that, we have to create mockup data.

  • Create a new file “MockHttpClient.ts” inside the src > webparts > PnPjsHelloWorld.
  • Copy the following code to the file.
    1. //import ISPList interface to this file from PnPjsHelloWorldWebPart.ts  
    2. import {  
    3.     ISPList  
    4. } from './PnPjsHelloWorldWebPart';  
    5. //Declare ISPList array and returns the array of items whenever MockHttpClient.get() method called  
    6. export default class MockHttpClient {  
    7.     private static _items: ISPList[] = [{  
    8.         Title: 'Mock List',  
    9.         Id: '1'  
    10.     }];  
    11.     public static get(restUrl: string, options ? : any): Promise < ISPList[] > {  
    12.         return new Promise < ISPList[] > ((resolve) => {  
    13.             resolve(MockHttpClient._items);  
    14.         });  
    15.     }  
    16. }  
  • Save the file.

  • Then, we have to import the MockHttpClient module in PnPjsHelloWorldWebPart.ts file.

    So, pen PnPjsHelloWorldWebPart.ts file. 

    Copy the following code just below the line import { IPnPjsHelloWorldWebPartProps } 

    from './IPnPjsHelloWorldWebPartProps';

    import MockHttpClient from './MockHttpClient';

  • Add the following private method inside the PnPjsHelloWorldWebPart class.
    1. private _getMockListData(): Promise < ISPList[] >  
    2.   {  
    3.     return MockHttpClient.get(this.context.pageContext.web.absoluteUrl).then(() => {  
    4.         const listData: ISPList[] = [{  
    5.             Title: 'Mock List',  
    6.             Id: '1'  
    7.         }, {  
    8.             Title: 'Mock List Two',  
    9.             Id: '2'  
    10.         }, {  
    11.             Title: 'Mock List Three',  
    12.             Id: '3'  
    13.         }];  
    14.         return listData;  
    15.     }) as Promise < ISPList[] > ;  
    16. }  
  • Save the file.

Retrieve List info from SharePoint site

  • Let’s update the files to retrieve the information from SharePoint site.

  • Open PnPjsHelloWorldWebPart.ts file. 

  • Add the following line to import the PnP JavaScript library in PnPjsHelloWorldWebPart.ts and use the PnP JS methods and properties.

    import pnp from 'sp-pnp-js';

  • Add the following private method inside the PnPjsHelloWorldWebPart class to retrieve the visible lists from SharePoint, using PnP JavaScript Library.
    1. private _getListData(): Promise < ISPList[] >  
    2.   {  
    3.     return pnp.sp.web.lists.filter('Hidden eq false').select('Title,Id').get().then((response) => {  
    4.         return response;  
    5.     });  
    6. }  
    In the above code, we are retrieving the list collection and filtering it to get the non-hidden lists. The response variable returns the array of List objects in the form of ISPList[].

Render the retrieved lists information

We have to render two different informations based on the workbench environment. For Local workbench, we have to render the mockup data. For SharePoint site workbench, we have to render the actual lists information.

To identify the environment, first import the EnvironmentType module to PnPjsHelloWorldWebPart.ts file.

  • Open PnPjsHelloWorldWebPart.ts file.

  • Add the following line to the import section in top of the page. 
    import { EnvironmentType } from '@microsoft/sp-client-base';

  • Add the following private method to determine the environment and based on that call, the required get methods to retrieve the array of ISPList collection for appropriate environment.
  1. private _renderListAsync(): void  
  2. {  
  3.     // Local environment  
  4.     if (this.context.environment.type === EnvironmentType.Local) {  
  5.         this._getMockListData().then((response) => {  
  6.             this._renderList(response);  
  7.         });  
  8.     }  
  9.     //SharePoint Site environment  
  10.     else {  
  11.         this._getListData().then((response) => {  
  12.             this._renderList(response);  
  13.         });  
  14.     }  
  15. }  
  • Add the following method to render the information to the UI based on the retrieved ISPList array collection,
    1. private _renderList(items: ISPList[]): void  
    2. {  
    3.     let html: string = '';  
    4.     items.forEach((item: ISPList) =>   
    5.     {  
    6.         html += `  
    7. <ul class="${styles.list}">  
    8. <li class="${styles.listItem}">  
    9. <span class="ms-font-l">${item.Title}</span>  
    10. </li>  
    11. </ul>`;  
    12.     });  
    13.     const listContainer: Element = this.domElement.querySelector('#spListContainer');  
    14.     listContainer.innerHTML = html;  
    15. }  
    We can apply the style to the element from another file by importing the css mod.

    ${styles.list} applies the style to the Ul element the style information is retrieved from.

  • Replace the WebPart render method contents with the following one.
    1. this.domElement.innerHTML = `  
    2. <div class="${styles.pnPjsHelloWorld}">  
    3. <div class="${styles.container}">  
    4. <div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  
    5. <div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">  
    6. <span class="ms-font-xl ms-fontColor-white">Welcome to SharePoint!</span>  
    7. <p class="ms-font-l ms-fontColor-white">Customize SharePoint experiences using Web Parts.</p>  
    8. <p class="ms-font-l ms-fontColor-white">${this.properties.description}</p>  
    9. <a href="https://github.com/SharePoint/sp-dev-docs/wiki" class="ms-Button ${styles.button}">  
    10. <span class="ms-Button-label">Learn more</span>  
    11. </a>  
    12. </div>  
    13. </div>  
    14. <div id="spListContainer" />  
    15. </div>  
    16. </div>`;  
    17.   
    18. this._renderListAsync();  
  • Save the file.

Test the application

  • Run “gulp serve” command in command line tool. That compiles the project and generates the JS and CSS files required for the application.

    application

  • Local workbench automatically starts after running the command. The default location for local workbench is

     http://localhost:4321/temp/workbench.html

    The typescript files and PnP js files are bundled into

    http://localhost:4321/dist/pn-pjs-hello-world.bundle.js

    files

  • Click + icon and select WebPart name “PnPjsHelloWorld” to insert the WebPart to the workbench to test the application. In local workbench, we will get the mockup data in the output.

    output

  • Open SharePoint site where we have uploaded workbench.aspx file, to test the application. Allow unsafe scripts to load in the page to access JavaScript and other dependent files from localhost.

  • In the workbench page, click + icon and then select the web part name to insert the SharePoint framework web part to the page,

    output

    Now, we have retrieved the lists which are not hidden in a current site. PnP JavaScript Library returns the success response as a collection of objects, whereas REST returns the response in a JSON format and then we have to convert the JSON value to object or object collection. Click here to view the same article from my blog.

Conclusion

In this article, we learned how to use a PnP JavaScript Library to access the SharePoint list collection and render the data in SharePoint Framework web part.