Create list in SharePoint Online using SPFx (SharePoint Framework)

Create list in SharePoint Online using SPFx (SharePoint Framework)

One comment

Loading

Create list in SharePoint Online using SPFx – in this article, we will learn about how to create a list in SharePoint Online using the SPFx (SharePoint Framework).

Key-Highlights: Create list in SharePoint Online using SPFx

  • Project Scaffolding process
  • Install the PnP JS Module
  • Add custom list to SharePoint Online method (function)
  • Description – add a custom list to SharePoint Online method (function)
  • CreateListUsingSpfxWebPart.ts file entire code
  • Verify the web part from the SharePoint Online page

Project Scaffolding process: Create list in SharePoint Online using SPFx

Create a Project folder name as “Create List Using SPFx” using the below command:

C:\Temp\SPFx>md "Create List Using SPFx"

Navigate to the newly created folder.

C:\Temp\SPFx>cd "Create List Using SPFx"

C:\Temp\SPFx\Create List Using SPFx>

Now, run the yeoman SharePoint Generator command – yo @microsoft/sharepoint

C:\Temp\SPFx\Create List Using SPFx>yo @microsoft/sharepoint

Hit enter, then enter the parameters when it asked as below:

Let’s create a new SharePoint solution.
? What is your solution name? create-list-using-sp-fx
? Which baseline packages do you want to target for your component(s)? SharePoint Online only (latest)
? Where do you want to place the files? Use the current folder
Found npm version 6.14.7
? Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without
running any feature deployment or adding apps in sites? No
? Will the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant? No
? Which type of client-side component to create? WebPart
Add new Web part to solution create-list-using-sp-fx.
? What is your Web part name? create-list-using-spfx
? What is your Web part description? create-list-using-spfx description
? Which framework would you like to use? (Use arrow keys)
> No JavaScript framework
React
Knockout

Note:

  • The above highlighted bold is the passed as input parameters.

Now, the project scaffolding process will start, this will take some time to complete, so have a little patience. 🙂

Create list in SharePoint Online using SPFx framework
Create a list in SharePoint Online using the SPFx framework

Run gulp build command to check project scaffolding is completed successfully.

SPFx Create list - gulp build command to check project scaffolding is completed successfully, create list in SharePoint Online using SPFx framework
SPFx Create list – gulp build command to check project scaffolding is completed successfully

Type “code .” (without quotation) in the command prompt (node.js) to open the project in visual studio.

Install the PnP JS Module: Create list in SharePoint Online using SPFx framework

Run the below command to install the PnP JS module.

npm install sp-pnp-js --save

This is how the PnP JS has been loaded to the project. We can refer to it in the project by using the below code:

import { Web } from "sp-pnp-js";

Add custom list to SharePoint Online method (function): Create list in SharePoint Online using SPFx framework

Below is the main ts file to create the list in SharePoint Online using the SPFx framework:

SPFx Create list in SharePoint Online using SPFx framework - main TS file code,
SPFx Create a list in SharePoint Online – main TS file code

Below is the main function to create the list in SharePoint Online using the SPFx framework:

private CreateListInSPOUsinPnPSPFx(): void 

    {  

        let myWeb = new Web(this.context.pageContext.web.absoluteUrl);  

        //let mySPFxListTitle = "CustomList_using_SPFx_Framework"; 

        let mySPFxListTitle = document.getElementById('listTitle')["value"];  

        let mySPFxListDescription = "Custom list created using the SPFx Framework";  

        let listTemplateID = 100;  

        let boolEnableCT = false;  

        myWeb.lists.add(mySPFxListTitle, mySPFxListDescription, listTemplateID, boolEnableCT).then(function(splist)

        {  

            document.getElementById("ListCreationStatusInSPOnlineUsingSPFx").innerHTML += `The SPO new list ` + mySPFxListTitle + ` has been created successfully using SPFx Framework.`;  

        });  

    }  

Description – Add custom list to SharePoint Online method (Create list in SharePoint Online using SPFx framework)

The explanation of the above codes is as below:

let myWeb = new Web(this.context.pageContext.web.absoluteUrl);

Using this above line of code, the web part gets connected with the current SharePoint site (where the web part is deployed or hosted).

The below list of lines just takes the list creation input like the title of the list, description of the list, template id of the list, whether the list content type is enabled or not (boolean), etc.

let mySPFxListTitle = document.getElementById('listTitle')["value"];

        let mySPFxListDescription = "Custom list created using the SPFx Framework";

        let listTemplateID = 100;

        let boolEnableCT = false;
In the below line of codes, add the list to the list collection of the current web with all the parameters mentioned above and display the list creation status to the user.
myWeb.lists.add(mySPFxListTitle, mySPFxListDescription, listTemplateID, boolEnableCT).then(function(splist)

        {

            document.getElementById("ListCreationStatusInSPOnlineUsingSPFx").innerHTML += `The SPO new list ` + mySPFxListTitle + ` has been created successfully using SPFx Framework.`;

        });
Note:
  • Whatever the programming language you may opt for but the logic or way of passing the parameters to the inbuilt myWeb.lists.add() method is same.

CreateListUsingSpfxWebPart.ts file entire code (Create list in SharePoint Online using SPFx framework)

This is the main web part file where the code is located.

import {  

    Web  

} from "sp-pnp-js";  

import {  

    Version  

} from '@microsoft/sp-core-library';  

import {  

    BaseClientSideWebPart,  

    IPropertyPaneConfiguration,  

    PropertyPaneTextField  

} from '@microsoft/sp-webpart-base';  

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

import * as strings from 'CreateListUsingSpfxWebPartStrings';  

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

export interface ICreateListUsingSpfxWebPartProps

{

  description: string;

}

export default class CreateListUsingSpfxWebPart extends BaseClientSideWebPart < ICreateListUsingSpfxWebPartProps >

 {  

    public render(): void

    {  

        this.domElement.innerHTML = `

<div class="${styles.createListUsingSpfx}">  

<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" style="font-size:28px">Welcome to SPFx learning (create list using PnP JS library)</span>  

<p class="ms-font-l ms-fontColor-white" style="text-align: left">Demo : Create SharePoint List in SPO using SPFx</p>  

</div>  

</div>  

<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">  

<div data-role="main" class="ui-content">    

             <div >    

                

               

               <input id="listTitle"  placeholder="List Name"/>  

               

               <button id="createNewCustomListToSPO"  type="submit" >Create List</button>    

                 

             </div>    

           </div> 

<br>  

<div id="ListCreationStatusInSPOnlineUsingSPFx" />  

</div>  

</div>  

</div>`;  

        this.AddEventListeners();  

    }  

    private CreateListInSPOUsinPnPSPFx(): void 

    {  

        let myWeb = new Web(this.context.pageContext.web.absoluteUrl);  

        //let mySPFxListTitle = "CustomList_using_SPFx_Framework"; 

        let mySPFxListTitle = document.getElementById('listTitle')["value"];  

        let mySPFxListDescription = "Custom list created using the SPFx Framework";  

        let listTemplateID = 100;  

        let boolEnableCT = false;  

        myWeb.lists.add(mySPFxListTitle, mySPFxListDescription, listTemplateID, boolEnableCT).then(function(splist)

        {  

            document.getElementById("ListCreationStatusInSPOnlineUsingSPFx").innerHTML += `The SPO new list ` + mySPFxListTitle + ` has been created successfully using SPFx Framework.`;  

        });  

    }  

    private AddEventListeners() : void

    {    

      

     document.getElementById('createNewCustomListToSPO').addEventListener('click',()=>this.CreateListInSPOUsinPnPSPFx());    

         

    }   

    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  

                        })  

                    ]  

                }]  

            }]  

        };  

    }  

}

Verify the web part from the SharePoint Online page: Create list in SharePoint Online using the SPFx framework

Run the gulp serve command from the node.js command prompt and add this web part to SharePoint Online like below:

We need to add the web part to this page – https://globalsharepoint2020.sharepoint.com/_layouts/15/workbench.aspx

Enter the list name in the list name textbox, then click on the “Create List” button.

Create list in SharePoint Online using SPFx demo
Create a list in SharePoint Online using the SPFx demo

Output – the below-highlighted list just got created thru the code.

Create list in SharePoint Online using the SPFx framework demo output
Create a list in SharePoint Online using SPFx demo output

Source code: Create list in SharePoint Online using SPFx framework

The above source can be downloaded from here.

Summary: Create list in SharePoint Online using SPFx framework

Thus, in this article, we have learned about how to create a list in SharePoint Online using the SPFx (SharePoint Framework) and the PnP JS library.

See Also: SPFx Framework Tutorial in SharePoint Online

You may also like the below SharePoint SPFx articles:

Download SharePoint Online PDF Book

Download SharePoint Online & Office 365 Administration eBook

Buy the premium version of SharePoint Online & Office 365 administration eBook from here:



Buy SharePoint Online & Office 365 Administration eBook


 

Get the free demo PDF eBook from here:

FREE DOWNLOAD

Send download link to:

Subscribe to get exclusive content and recommendations every month. You can unsubscribe anytime.

About Post Author

1 comments on “Create list in SharePoint Online using SPFx (SharePoint Framework)”

Do you have a better solution or question on this topic? Please leave a comment