Retrieve SharePoint list items using SharePoint framework (SPFx)

This SPFx tutorial, we will discuss how to retrieve SharePoint list items using spfx and typescript in SharePoint Online modern experience.

SharePoint Framework is the new development model and it is a page and Web part model which provides full support for client-side SharePoint development, easy integration with SharePoint data, and support for open-source tooling.

With SharePoint Framework, you can use modern Web technologies and the tools in your preferred development environment to build productive experiences and apps in SharePoint.

Retrieve SharePoint list items using SharePoint framework

Follow the below steps to Get the List items using SharePoint Rest Interface and Typescript.

Create SPFx Solution

Step 1: Create a new Solution for example “GetSPListItems”

  • Open the command prompt. Create a directory for SPFx solution.
    • md GetSPListItems
  • Navigate to the above-created directory
    • cd GetSPListItems

Step 2: Run Yeoman SharePoint Generator to create the solution.

  • yo @microsoft/sharepoint

Yeoman generator will present you with the wizard by asking questions about the solution to be created.

  • Solution Name: Hit Enter to have a default name (GetSPListItems in this case) or type in any other name for your solution.
  • Target for 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 will be accessible everywhere. Select choice – N (install on each site explicitly)
  • Type of client-side component to create: We can choose to create client-side web part or an extension. Choose the web part option. Select option – WebPart.
  • Web part name: Hit enter to select the default name or type in any other name. Type name – getSPListItems
  • Web part description: Hit enter to select the default description or type in any other value.
  • Framework to use: Select any JavaScript framework to develop the component. Available choices are No JavaScript Framework, React, and Knockout. Select option – No JavaScript Framework

Step 3: In the command prompt type the below command to open the solution in vs code editor-> ” code .

retrieve sharepoint list items using sharepoint framework
retrieve sharepoint list items using sharepoint framework

Step 4: go to the “GetSPListItems.ts” file, copy and paste the below code.

import { Version } from '@microsoft/sp-core-library';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import {
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { escape } from '@microsoft/sp-lodash-subset';

import styles from './GetSpListItemsWebPart.module.scss';
import * as strings from 'GetSpListItemsWebPartStrings';

import {
  SPHttpClient,
  SPHttpClientResponse   
} from '@microsoft/sp-http';
import {
  Environment,
  EnvironmentType
} from '@microsoft/sp-core-library';

export interface IGetSpListItemsWebPartProps {
  description: string;
}
export interface ISPLists {
  value: ISPList[];
}

export interface ISPList {
  Title: string;
  Conros_ProductCode : string;
  Conros_ProductDescription :string;
}
  
export default class GetSpListItemsWebPart extends BaseClientSideWebPart<IGetSpListItemsWebPartProps> {
  private _getListData(): Promise<ISPLists> {
    return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('Conros Products')/Items",SPHttpClient.configurations.v1)
        .then((response: SPHttpClientResponse) => {
        return response.json();
        });
    }
    private _renderListAsync(): void {
    
      if (Environment.type == EnvironmentType.SharePoint || 
               Environment.type == EnvironmentType.ClassicSharePoint) {
       this._getListData()
         .then((response) => {
           this._renderList(response.value);
         });
     }
   }
    private _renderList(items: ISPList[]): void {
      let html: string = '<table border=1 width=100% style="border-collapse: collapse;">';
      html += '<th>Title</th> <th>Product Code</th><th>Product Description</th>';
      items.forEach((item: ISPList) => {
        html += `
        <tr>            
            <td>${item.Title}</td>
            <td>${item.Conros_ProductCode}</td>
            <td>${item.Conros_ProductDescription}</td>
            
            </tr>
            `;
      });
      html += '</table>';
    
      const listContainer: Element = this.domElement.querySelector('#spListContainer');
      listContainer.innerHTML = html;
    }
      
  public render(): void {
    this.domElement.innerHTML = `
      <div class="${ styles.getSpListItems }">
        <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>List Items</div>
          <br>
           <div id="spListContainer" />
        </div>
      </div>`;
      this._renderListAsync();
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

Step5: In the command prompt, type “gulp serve” .

Step 6: Go to sharepoint workbench URL is
https://domain-name/sites/site collection name/_layouts/15/workbench.aspx

Step 7: In the SharePoint local workbench page, add the web part. Sharepoint list items will be displayed in the web part.

retrieve sharepoint list items using spfx
retrieve sharepoint list items using spfx

You may like following SharePoint framework tutorials:

You may also like following SharePoint Framework tutorials:

Hope this SharePoint framework tutorial explains, how to retrieve sharepoint list items using rest api & typescript in sharepoint framework model.

  • >