Create A Webpart Which will retrieve the List and Document using SPFx
Softree Technology > Blogs > SharePoint > Create A Webpart Which will retrieve the List and Document using SPFx

Create A Webpart Which will retrieve the List and Document using SPFx

  • Posted by: Softree Technology

In this Blog, we are going to discuss about the creation of a new webpart using SPFx(No JavaScript framework).This webpart will represent the data of the corresponding site such as website Name ,website URL ,Total List Count & retrieves the name of all custom list and documents.

Let us get started …

Step-A:(Creation of Webpart):

Open Command Prompt. Go to the drive in which you want to create the Project. Here I have created the project in “c-drive”.

Run the below commands

  • cd C:\
  • md Webpart

Refer image-1 for more details.

Image:1

Refer image-2 and run the command “yo @microsoft/sharepoint”. Then Enter the asked details same as mentioned in Image-2 to create the webpart. The webpart creation may take some time so wait to complete the installation.

After completion, you can see a Congratulation message (Check Image-3).

Image:2

Image:3

Then run the command code .” to open the Visual studio code.

Expand src-> webparts (Refer image-4) to open the files.

Image:4

Step-B:(Create a New File):

Create a new file inside C: \WebPart\src\webparts\dynamicWp. Name it as “GetList.ts” as shown in image:5.

Image:5

Image:6

Step-C:(Change the code):

Here I have mentioned the code for corresponding files. So please refer the instructions accordingly and add/change the code.

  • In “DynamicWPWebPart.ts” replace the below code.

import pnp from “sp-pnp-js”;

import { Version } from ‘@microsoft/sp-core-library’;

import {

  IPropertyPaneConfiguration,

  PropertyPaneTextField ,

  PropertyPaneDropdown

} from ‘@microsoft/sp-property-pane’;

import { BaseClientSideWebPart } from ‘@microsoft/sp-webpart-base’;

import { escape } from ‘@microsoft/sp-lodash-subset’;

import styles from ‘./DynamicWpWebPart.module.scss’;

import * as strings from ‘DynamicWpWebPartStrings’;

import MockHttpClient from ‘./GetList’;

import{

  SPHttpClient,

  SPHttpClientResponse

}from ‘@microsoft/sp-http’;

import {

  Environment,

  EnvironmentType

} from ‘@microsoft/sp-core-library’;

import “@pnp/sp/webs”;

import “@pnp/sp/lists”;

import { _List} from ‘@pnp/sp/lists/types’;

export interface IDynamicWpWebPartProps {

  description: string;

  List:string;

}

export interface ISPLists {

  value: ISPList[];

}

export interface ISPList {

  Title: string;

  Id: string;

  BaseTemplate: string;

}

let array:string[];

export default class DynamicWpWebPart extends BaseClientSideWebPart<IDynamicWpWebPartProps> {

  private _renderList(): void {

    if (Environment.type === EnvironmentType.Local) {

      this._getItemsFromList().then((response) => {

        this._listDesign(response.value);

      });

    }

    else if (Environment.type == EnvironmentType.SharePoint ||

             Environment.type == EnvironmentType.ClassicSharePoint) {

      this._getListData()

        .then((response) => {

          this._listDesign(response.value);

        });

    }

  }

  private _listDesign(items: ISPList[]): void {

    let html: string = ”;

    let i =0;

    html+=`

    <div><p class=”${ styles.label} style=”margin:5px;5px;5px;5px; font-weight: bold”>Total List Count : ${items.length}</p>

    </div>`;

    html +=`<div><b style=”font-size:20px;”>Document</b>`

    items.forEach((item: ISPList) => {

      if (item.BaseTemplate==’101′) {

        html += `

    <ul class=”${styles.list}”>

      <li class=”${styles.listItem}”>

        <span class=”ms-font-l”>Document Title : <b>${item.Title}</b></span>

      </li>

    </ul>`;

      }

    });

    html +=` </div>`;

    html +=`<div><b style=”font-size:20px;”>List</b>`

    items.forEach((item1: ISPList) => {

      if(item1.BaseTemplate==’100′){

        html += `

        <ul class=”${styles.list}”>

        <li class=”${styles.listItem}”>

          <span class=”ms-font”>List Title : <b>${item1.Title}</b></span>

        </li>

      </ul>`

      }

    });

    html +=` </div>`;

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

    listContainer.innerHTML = html;

  }

  private _getListData(): Promise<ISPLists> {

    return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists?$filter=Hidden eq false`, SPHttpClient.configurations.v1)

      .then((response: SPHttpClientResponse) => {

        return response.json();

      });

  }

  private _getItemsFromList(): Promise<ISPLists> {

    return MockHttpClient.get()

      .then((data: ISPList[]) => {

        var listData: ISPLists = { value: data };

        return listData;

      }) as Promise<ISPLists>;

  }

  public render(): void {

    this.domElement.innerHTML = `<textarea placeholder=”DynamicWP” aria-label=”Add a title” style=”height: 23px; border:none;font-size:20px;font-weight: bold; width: 100%;”></textarea>

        <div class=”${ styles.dynamicWp }”>

          <div class=”${ styles.container }”>

            <div class=”${ styles.row }”>

              <div class=”${ styles.column }”>

              <div><p class=”${ styles.label} style=”margin:5px;5px;5px;5px; font-weight: bold”>WebSite Name : ${escape(this.context.pageContext.web.title)}</p></div>

              <div><p class=”${ styles.label} style=”margin:5px;5px;5px;5px; font-weight: bold”>WebSite URL : ${escape(this.context.pageContext.site.absoluteUrl)}</p></div>               

              <div id=”spListContainer”/>

              <p class=”${ styles.description }”>${escape(this.properties.description)}</p>

              </div>

            </div>

          </div>

        </div>`;

      this._renderList();

  }

  protected get dataVersion(): Version {

    return Version.parse(‘1.0’);

  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {

      return {

      pages: [

        {

          header: 

          {

            description: strings.PropertyPaneDescription,

            list : strings.List

          },

          groups: [

            {

              groupName: strings.BasicGroupName,

              groupFields: [

                PropertyPaneTextField(‘Description’, {

                  label: strings.DescriptionFieldLabel

                })

              ]

            }

          ]

        }

      ]

    };

  }

}

  • In “GetList.ts” add the below code.

import { ISPList } from ‘./DynamicWpWebPart’;

export default class GetDemoList  {

  private static _items: ISPList[] = [{ Title: ‘List 1′,BaseTemplate:’101’,Id: ‘1’ },

                                      { Title: ‘List 2′,BaseTemplate:’101’ ,Id: ‘2’ },

                                      { Title: ‘List 3′,BaseTemplate:’101’, Id: ‘3’ , }];

  public static get(): Promise<ISPList[]> {

    return new Promise<ISPList[]>((resolve) => {

      resolve(GetDemoList._items);

    });

  }

}

  • In “mystrings.d.ts” replace the below code.

declare interface IDynamicWpWebPartStrings {

  PropertyPaneDescription: string;

  BasicGroupName: string;

  DescriptionFieldLabel: string;

  List:string;

}

declare module ‘DynamicWpWebPartStrings’ {

  const strings: IDynamicWpWebPartStrings;

  export = strings;

}

  • In “en-us.js” replace the below code.

define([], function() {

  return {

    “PropertyPaneDescription”: “Description”,

    “BasicGroupName”: “Group Name”,

    “DescriptionFieldLabel”: “Description Field”,

    “ListFieldLable” : “Lists”

  }

});

  • In DynamicWpWebPart.module.scss” replace the below code.

@import ‘~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss’;

.dynamicWp {

  .container {

    max-width: 700px;

    margin: 0px auto;

    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);

  }

  .row {

    @include ms-Grid-row;

    @include ms-fontColor-white;

    background-color: $ms-color-themeDark;

    padding: 20px;

  }

  .column {

    @include ms-Grid-col;

    @include ms-lg10;

    @include ms-xl8;

    @include ms-xlPush2;

    @include ms-lgPush1;

  }

  .title {

    @include ms-font-xl;

    @include ms-fontColor-white;

  }

  .subTitle {

    @include ms-font-l;

    @include ms-fontColor-white;

  }

  .description {

    @include ms-font-l;

    @include ms-fontColor-white;

  }

  .button {

    // Our button

    text-decoration: none;

    height: 32px;

    // Primary Button

    min-width: 80px;

    background-color: $ms-color-themePrimary;

    border-color: $ms-color-themePrimary;

    color: $ms-color-white;

    // Basic Button

    outline: transparent;

    position: relative;

    font-family: “Segoe UI WestEuropean”,”Segoe UI”,-apple-system,BlinkMacSystemFont,Roboto,”Helvetica Neue”,sans-serif;

    -webkit-font-smoothing: antialiased;

    font-size: $ms-font-size-m;

    font-weight: $ms-font-weight-regular;

    border-width: 0;

    text-align: center;

    cursor: pointer;

    display: inline-block;

    padding: 0 16px;

    .label {

      font-weight: $ms-font-weight-semibold;

      font-size: $ms-font-size-m;

      height: 32px;

      line-height: 32px;

      margin: 0 4px;

      vertical-align: top;

      display: inline-block;

    }

  }

  .list {

    color: #333333;

    font-family: ‘Segoe UI Regular WestEuropean’, ‘Segoe UI’, Tahoma, Arial, sans-serif;

    font-size: 14px;

    font-weight: normal;

    box-sizing: border-box;

    background-color: #ffffff;

    margin: 10;

    padding: 10;

    line-height: 50px;

    list-style-type: none;

    box-shadow: 0 4px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);

  }

  .listItem {

    color: #333333;

    vertical-align: center;

    font-family: ‘Segoe UI Regular WestEuropean’, ‘Segoe UI’, Tahoma, Arial, sans-serif;

    font-size: 14px;

    font-weight: normal;

    box-sizing: border-box;

    margin: 0;

    padding: 0;

    background-color: #ffffff;

    box-shadow: none;

    *zoom: 1;

    padding: 9px 28px 3px;

    position: relative;

  }

}

Step-D:(Add the webpart):

After following the above steps save all the files. In command prompt run the command “gulp serve”. The browser will open automatically and by clicking on the plus sign you can add the webpart DynamicWP. (Refer image-7).

Image:7

The final webpart will appear as below image. (Refer image-8).

Image:8

Keywords:

1-Create A Modern Web Part which will retrieve the Lists and Documents using SPFX.
2-Retrieve lists and Documents Title using SPFX.
3-How to retrieve lists and documents Title information within a modern Web Part.

Author: Softree Technology

Leave a Reply