Create a SharePoint Framework Client WebPart – Retrieve List Items

Total visits : 2472

Microsoft announce the first public developer preview of the SharePoint Framework. With this initial release, you can start building client-side WebPart.

In this post I am creating a first Client WebPart – Modern SharePoint Development

Prerequisites

  1. Setup SharePoint Tenant
    • https://jenkinsblogs.sharepoint.com/sites/dev
  2. Setup your machine
  3. First Webpart

My Webpart Name : FirstWebpart

Follow the above prerequisites and develop a First Webpart, screenshot below

FirstWebpart

In this post I am showing how to retrive list items and display as Table format.

listItems

Step 1 – Create a List

  • Created a Custom List named “MyList”
  • Added one more column called “Description”
  • Added 4 Items, see below

listItem

 

 

 

 

 

 

Open cmd and move to your project folder using cd helloworld-webpart
Open Visual Code type Code .

To Execute gulp serve

Steps to display List Items in Client WebPart

Step2 – Replace the rendering code

  • I have removed some of the default HTML rendered code in the FirstWebpartWebPart.ts file.
  • Added below code

<div class=”${styles.firstWebpart}”>
  <div class=”${styles.container}”>
    <div class=”ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}”>
      <div class=”ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1″>
        <span class=”ms-font-xl ms-fontColor-white”>Welcome to SharePoint Modern Developmennt</span>
        <p class=’ms-font-l ms-fontColor-white’>Loading from ${this.context.pageContext.web.title}</p>
        <p class=”ms-font-l ms-fontColor-white”>Retrive Data from SharePoint List</p>
      </div>
    </div>
    <div class=”ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}”>
    <div>My List Items</div>
    <br>
<div id=”spListContainer” />
    </div>
  </div>
</div>`;

this._renderListAsync();

Step 3 – Define List Item Model interfaces…

Open FirstWebpartWebPart.ts file Switch to Visual Studio Code and navigate to src\webparts\helloWorld\FirstWebpartWebPart.ts

Copy and Paste the below code above the class FirstWebpartWebPart

export interface ISPLists {
  value: ISPList[];
}

export interface ISPList {
  Title: string;
  Id: string;
  Description: string;
}

We have three columns (Title, ID, Description)

Step 4 – Create a Mock class to display while test from local, i.e without connect SharePoint.

Create a new file MockHttpClient.ts in \src\webparts\FirstWebpart folder

Copy the following code into  MockHttpClient.ts

import { ISPList } from ‘./FirstWebpartWebPart’;

export default class MockHttpClient {

    private static _items: ISPList[] = [{ Title: ‘Mock List’, Id: ‘1’, Description: ‘sample’}];

    public static get(restUrl: string, options?: any): Promise<ISPList[]> {
      return new Promise<ISPList[]>((resolve) => {
            resolve(MockHttpClient._items);
        });
    }
}

Save the file.

Method to retrieve mock data
Open FirstWebpartWebPart.ts file Switch to Visual Studio Code and navigate to src\webparts\helloWorld\FirstWebpartWebPart.ts

Copy the following code just below import section
import MockHttpClient from ‘./MockHttpClient’;

Add the following private method to mock list retrieval inside the FirstWebpartWebPart class

private _getMockListData(): Promise<ISPLists> {
    return MockHttpClient.get(this.context.pageContext.web.absoluteUrl).then(() => {
        const listData: ISPLists = {
            value:
            [
                { Title: ‘Mock List One’, Id: ‘1’, Description: ‘sample’ },
                { Title: ‘Mock List Two’, Id: ‘2’, Description: ‘sample’ },
                { Title: ‘Mock List Three’, Id: ‘3’, Description: ‘sample’ }
            ]
            };

        return listData;
    }) as Promise<ISPLists>;
}

Save it.

Step 4 – Retrive List Items from SharePoint List

To render list information add the below code in Import section

import { EnvironmentType } from ‘@microsoft/sp-client-base’;

Add the following private methods to list retrieval inside the FirstWebpartWebPart class

private _getListData(): Promise<ISPLists> {
return this.context.httpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/GetByTitle(‘MyList’)/Items`)
    .then((response: Response) => {
    return response.json();
    });
}
  private _renderListAsync(): void {
  // Local environment
  if (this.context.environment.type === EnvironmentType.Local) {
    this._getMockListData().then((response) => {
      this._renderList(response.value);
    }); }
    else {
    this._getListData()
      .then((response) => {
        this._renderList(response.value);
      });
  }
}

To render List Items
private _renderList(items: ISPList[]): void {
  let html: string = ‘<table border=1 width=100% style=”border-collapse: collapse;”>’;
  html += `<th>ID</th><th>Title</th><th>Description</th>`;
  items.forEach((item: ISPList) => {
    html += `
    <tr>
        <td>${item.Id}</td>
        <td>${item.Title}</td>
        <td>${item.Description}</td>
        </tr>
        `;
  });
  html += `</table>`;

  const listContainer: Element = this.domElement.querySelector(‘#spListContainer’);
  listContainer.innerHTML = html;
}

Save the webpart file and Build it.

Notice in the gulp serve console window that it rebuilds the code. Make sure you don’t see any errors.

Below the output screenshot

FirstWebpartWithList

Good Luck,

Attached the files below (FirstWebpartWebPart.ts and MockHttpClient.ts)

WinZip_thumb

 

 

 

 

  • Mary

    It is really really useful to me.Thank You so much and its a very nice article.Please let me know if it can be implemented using Angular js(Typescript) 🙂

    • Thank you
      Yes we can implement using Angularjs, reactjs, knockout, nodejs and etc…
      I going to write another article – How to implement using angular js.

      • Mary

        I have implemented above article and it worked for me.Thank you so much for that.Please update me once you are done with Angular code 🙂 .Thank You in advance!!

  • Savan Gupta

    Thanks,It was the best example.

    Really Helpful. I was looking for the adding,updating and deletion of the SharePoint list item.