Create a SharePoint List using SharePoint Framework [Including Adding Columns]

A few days back, I was working on a SharePoint Framework project for a client based in Australia. One requirement was to create a few SharePoint Online lists, including different types of columns. So, I decided to develop an SPFx client-side side webpart that will create a SharePoint list and add columns using SPFx code.

By the end of the tutorial, you will learn the following things:

  • Create a SharePoint Online list
  • Rename the SharePoint list display name
  • Enable the SharePoint list to appear in the SharePoint site quick launch navigation
  • Add various types of columns to the SharePoint list, such as single line of text, multiline of text, number, choice, datetime, etc.
  • Add the newly added columns to the SharePoint list default view

For this particular example, the webpart will have a button. When a user clicks on the button, it will create the SharePoint list, update the list display name, enable the quick launch properties, add the columns, rename the default title column, update the list column display names, and finally, it will add the columns to the default view of the SharePoint list.

It will create a SharePoint list like the one below:

spfx with pnp to display the sharepoint list on quick launch

All these operations will be done on a single button click. Interesting? Keep reading!

Note: We will use the PnPjs library to make Rest API calls to SharePoint.

Create a SharePoint List using the PnPJS Library in SPFX

Note: We’ll use PnP js libraries in the SharePoint Framework [SPFX] to make REST API calls to SharePoint.

To work with SPFx, you must first set up the development environment locally. I wrote a complete tutorial and made a video on this. Follow the steps below.

Create an SPFX Solution

1. Open any command prompt to create a new solution. Create one directory by providing the below cmd.

md CreateSPListwithColumns

2. To enter into that solution, provide the below cmd and click enter.

cd CreateSPListwithColumns

3. Run the below Yeoman generator cmd to quickly create a SharePoint client-side solution project with the right toolchain and project structure.

yo @microsoft/sharepoint

4. Then, it will ask you to fill in the following questions. Provide the answers that I have given below.

  • What is your solution name? = Click enter for the default name or type your own solution name.
  • Which type of client-side component to create? = Webpart
  • What is your Web part name? = CreateSPListwithColumns
  • Which template would you like to use? = No framework

5. Once it creates the project successfully, provide code . Clicking on enter takes you to VisualStudioCode.

To test this webpart while developing, you can use the SharePoint Workbench URL. To do this, you’ll need to update the Serve.json file with your SharePoint site address in the “initialPage” property.

"initialPage":   "https://tsinfotechnologies.sharepoint.com/sites/TSSharePointSite/_layouts/workbench.aspx"
how to create a list add columns to it in spfx

After updating the URL, just run the command below in Terminal once.

gulp serve

>> SharePoint Framework Training Course FREE <<

Install and Set Up @pnp/sp in SPFX Project

We need to install the @PnP/SP package so we can easily work with SharePoint lists in our SPFX project. Follow the steps below!

1. Run the command below in TERINAL. This step is standard for any project type(React, etc).

npm install @pnp/sp --save

2. Now, Open the src folder -> Webpart -> CreateSPListwithColumnsWebpart.ts file -> provide the below cmds under the imports.

import { spfi, SPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import { FieldTypes } from "@pnp/sp/fields/types";
import "@pnp/sp/fields";
import "@pnp/sp/views";
import "@pnp/sp/navigation";

Here:

CommandDescription
import { spfi, SPFx } from “@pnp/sp”1. sp = Provides a fluent API for working with SharePoint REST.
2. spfi = It is the main function of creating a SharePoint context or instance.
3. SPFX = It binds the PnPjs to the SharePoint Framework context, so it knows where and how to interact with SharePoint.
import “@pnp/sp/webs”Supports for working with SharePoint Webs, such as retrieving site properties, managing site features, etc.
import “@pnp/sp/lists” To interact with SharePoint lists and libraries and perform actions like Creating lists, adding or updating items, and retrieving data or properties.
import { FieldTypes } from “@pnp/sp/fields/types”FieldTypes from “@pnp/sp/fields/types” is used to define and specify the data types when creating fields.
import “@pnp/sp/fields”It provides methods to interact with SharePoint list fields, allowing the creation, retrieval, and updating of list fields and management field types.
import “@pnp/sp/views”It enables interaction with SharePoint list views. You can use it to retrieve, create, or modify views to control how list data is displayed.
import “@pnp/sp/navigation” Allows to manage the SharePoint site navigation, including editing the Quick Launch and top navigation bar.

Then, under the export default class structure, create a private variable for using the spfi context.

private sp: ReturnType<typeof spfi>;
SharePoint add column to list using spfx

3. Update the OnInIt method () with the below code.

  protected async onInit(): Promise<void> {
    this.sp = spfi().using(SPFx(this.context));
  }

Here, spfi().using(SPFx(this.context)) :

Binds the PnPjs library (spfi) to the SPFX context. This ensures PnPjs can authenticate requests and know which SharePoint site it works with.

how to create sharepoint online list using spfx

After updating, save the changes. Now, we’ll create a function that creates a SharePoint list along with columns.

Check out SPFx Send Email using PnP

Create a SharePoint List Using the PnPJs in the SPFX Project

To create a SharePoint list along with columns, add the below function within the export default class CreateSpListwithColumnsWebPart {…..} in the .ts file, like in the image below.

add columns to sharepoint list using spfx with pnp js
private async createListAndColumns(): Promise<void> {
    try {
      const internalListName = "EmployeeDetails";
      const displayListName = "Employee Details";

      // Create SharePoint list with internal name
      const createdList = await this.sp.web.lists.add(internalListName, displayListName, 100);

      //get List id
      const listId = createdList.Id;

      //update library internal name with display name.
      await this.sp.web.lists.getById(listId).update({ Title: displayListName });

      // Add to Quick Launch with the correct URL format for document libraries
      const listUrl = `./Lists/${internalListName}/AllItems.aspx`;  //url of list    
      await this.sp.web.navigation.quicklaunch.add(displayListName, listUrl , true);

      // Columns to add stored in library.
      const listTitle = displayListName;
      const columns = [
            { name: "EmployeeID", type: FieldTypes.Text, title: "Employee ID" },
            { name: "PhoneNumber", type: FieldTypes.Number, title: "Phone Number" },
            { name: "Address", type: FieldTypes.Note, title: "Address" },
            { name: "IsFresher", type: FieldTypes.Boolean, title: "Is Fresher" },
            { name: "Department", type: FieldTypes.Choice, title: "Department", choices: ["HR", "IT", "Marketing", "Sales", "Finance", "Research"] },
            { name: "JoiningDate", type: FieldTypes.DateTime, title: "Joining Date" },
            { name: "ProfileImage", type: FieldTypes.Image, title: "Profile Image" },
            { name: "Manager", type: FieldTypes.User, title: "Manager" }
        ];

    // Iterating over columns to add fields
    for (const column of columns) {
          if (column.type === FieldTypes.Choice) {
            await this.sp.web.lists.getByTitle(listTitle).fields.addChoice(column.name, {
              Group: "Custom Columns",
              Description: column.title,
              Required: false,
              Choices: column.choices || [],
             });
        } else {
          await this.sp.web.lists.getByTitle(listTitle).fields.add(column.name, column.type, {
          Group: "Custom Columns",
          Description: column.title,
          Required: false,
    });
  }
  // Update column display name after creation
  await this.sp.web.lists.getByTitle(listTitle).fields.getByInternalNameOrTitle(column.name).update({ Title: column.title });

    // Renaming the default Title field to "Country Name"
    const titleField = await this.sp.web.lists.getByTitle(displayListName).fields.getByInternalNameOrTitle('Title');
    await titleField.update({Title: "Employee Full Name"});


  // Add to the default view
  await this.sp.web.lists.getByTitle(listTitle).defaultView.fields.add(column.name);
}
      alert("Employee Details List and its columns created successfully!");
    } catch (error) {
      console.error("Error creating library or columns:", error);
      alert("Error creating list or columns. Please check the console.");
    }
  }

Let’s understand the code now:

  • createListAndColumns() = This is the custom function that creates a SharePoint list and makes this list visible on the Quick launch of the SharePoint site and adds multiple fields on different data types like text, number, choice, boolean, etc.
  • internalListName, displayListName= These variables store SharePoint list names with and without spaces.

For the remaining code explanation, follow the below sections one by one.

From the above custom function, the below PnP Js command will create the SharePoint List. So, let’s understand the command and what it takes to create a list.

const createdList = await this.sp.web.lists.add(internalListName, displayListName, 100);
  • Here, await will stop executing code until the list creation is finished.
  • this.sp.web.lists.add() method creates the SharePoint list with an internal name.
  • 100 = It indicates the SharePoint list template ID. For the library, it is 101.
  • createdList = This variable stores the created sharePoint list object that contains properties of the list. For example:
    • Title, ID, created time, Base Template, etc.,

Update the SharePoint List Name Using PnP Js in the SPFX Project

Above, we created the SharePoint list with the internal name, which contains no spaces. So, to update the SharePoint list display name with PnP Js commands in this SPFX project, we are using the commands below.

1. To do this, first, we need to fetch the created SharePoint list ID.

const listId = createdList.Id
  • listId variable fetching the list ID from the createdList object.

2. Provide that listed variable in the below command to fetch the list to update the SharePoint list name.

await this.sp.web.lists.getById(listId).update({ Title: displayListName });

Here:

  • Using the update() method, we’re changing the SharePoint list internal name with the display name.
  • displayListName = Variable contains the list display name.
  • To update the list, we require the list ID. So, in the getById() method, we’re passing the newly created list id.

Check out Create Folders and Subfolders in SharePoint document library using SPFx

Display the SharePoint List in the Quick Launch Bar using PnP Js in SPFX

In this section, we’ll see how to display the SharePoint list we created earlier in the Quick Launch bar using PnP Js in this SPFX project.

1. Make sure the below import command is present under the import { spfi, SPFx } from “@pnp/sp”;

import "@pnp/sp/navigation";

Then, we need to give the SharePoint list URL to the Quick Launch. So, below, I created a variable listUrl that stores the standard URL for the list.

  • const listUrl = `./Lists/${internalListName}/AllItems.aspx`;
  • ${internalListName} = ${} is used to fetch data dynamically, and internalListName is the variable that contains the SharePoint list’s internal name.

After getting the url, we need to provide it in the add() like below.

await this.sp.web.navigation.quicklaunch.add(displayListName, listUrl true);

Here:

  • quicklaunch.add() method will add the list url to the quick launch menu.
  • displayListName = Variables that store SharePoint display name.
  • listUrl = Variable stores the standard list URL.

Up to now, we have seen how to create a SharePoint list, update the list name, and make it visible in the quick launch using PnP js commands in the SPFX project.

Check out SPFx Application Customizer Example

Add Multiple Columns to SharePoint List using PnPJs Core in SPFX

Using PnP js, let’s create columns with different data types in the SharePoint list in the SPFX project. Here, I’m going to create below columns with the given data types:

Column NameData Type
Employee IDSingle line of text
Phone NumberNumber
AddressMultiple lines of text
Is FresherBoolean
DepartmentChoice [HR, IT, Marketing, Sales, Finance, Research]
Joining DateDate & Time
Profile ImageImage
ManagerPerson

Make sure the commands below are imported or not at the top of the code.

import { FieldTypes } from "@pnp/sp/fields/types";
import "@pnp/sp/fields";

I created an array named columns to store all the column data required for the SharePoint list.

      const columns = [
            { name: "EmployeeID", type: FieldTypes.Text, title: "Employee ID" },
            { name: "PhoneNumber", type: FieldTypes.Number, title: "Phone Number" },
            { name: "Address", type: FieldTypes.Note, title: "Address" },
            { name: "IsFresher", type: FieldTypes.Boolean, title: "Is Fresher" },
            { name: "Department", type: FieldTypes.Choice, title: "Department", choices: ["HR", "IT", "Marketing", "Sales", "Finance", "Research"] },
            { name: "JoiningDate", type: FieldTypes.DateTime, title: "Joining Date" },
            { name: "ProfileImage", type: FieldTypes.Image, title: "Profile Image" },
            { name: "Manager", type: FieldTypes.User, title: "Manager" }
        ];
  • The array contains all the column’s details as an object. That object has properties like:
    • name = Stores the internal name of the column.
    • type = Store the data type of the column.
    • title = Stores display name of the column.
    • choices =For the choice field, it stores choice values.

Then, using the for loop, we’re iterating over each object in the array. Then, add columns to the SharePoint list.

    for (const column of columns) {
          if (column.type === FieldTypes.Choice) {
            await this.sp.web.lists.getByTitle(listTitle).fields.addChoice(column.name, {
              Group: "Custom Columns",
              Description: column.title,
              Required: false,
              Choices: column.choices || [],
             });
        } else {
          await this.sp.web.lists.getByTitle(listTitle).fields.add(column.name, column.type, {
          Group: "Custom Columns",
          Description: column.title,
          Required: false,
    });
  }
}

Here

  • Using the if condition, I check that the column’s data type matches the choice. Then, with the addChoice() method, I add a choice field to the SharePoint list, which will also add the choice values.
  • column.name = Returns column internal name.
  • column.type = Returns column data type.
  • column.title = Returns column display name.
  await this.sp.web.lists.getByTitle(listTitle).fields.addChoice(.....)
  • For the remaining data types, using the add() method, I’m adding columns to the SharePoint list.
await this.sp.web.lists.getByTitle(listTitle).fields.add(..)

Check out SPFx Field Customizer Example

Rename SharePoint List Title Field using PnP Js in SPFX Project

To rename the SharePoint list title column, we need to fetch the title field, and then we need to update it with the custom name.

Here is the spfx code.

const titleField = 
await this.sp.web.lists.getByTitle(displayListName).fields.getByInternalNameOrTitle('Title');
  • titleField = Variable storing the SharePoint list title field, which is fetched from the getByInternalNameOrTitle() method.

Then, with the update() method, we’re giving the custom name to the Title field like below.

await titleField.update({Title: "Employee Full Name"});

Check out SPFx Property Pane Controls

Rename SharePoint List Field Names using PnP Js in the SPFX Project

To update the SharePoint list column names with their display names, we need to retrieve each column and use the Update() method to change its internal name with the display name.

Below is the code:

await this.sp.web.lists.getByTitle(listTitle).fields.getByInternalNameOrTitle(column.name).update({ Title: column.title });

Here,

  • column.name = Returns the column name.
  • column.title = Gives the display name of each column.

Add SharePoint List Fields to Default View using PnP Js in SPFX

We need to import the views module from the PnPjs library to display the columns visible in the default view of the SharePoint list. So ensure the below cmd is imported at the start of the code.

import "@pnp/sp/views";

Look at the code below, which makes all columns visible in the default view of the SharePoint list.

Note: The below cmd we included in the for loop, so after creating columns, renaming the title, and updating other fields’ display name, then control comes to this below cmd, and it makes all columns visible in the SharePoint list default view.

await this.sp.web.lists.getByTitle(listTitle).defaultView.fields.add(column.name)

Here,

  • defaultView.fields.add() method adds the columns to the default view.
  • column.name =Returns each column name.

So, up to here, we have covered creating a SharePoint list, updating the list name, displaying it in the SharePoint Online site quick launch bar, adding columns, etc., with code in the custom function.

Let’s see when this function needs to work and where we need to update the code in the .ts file in this spfx project.

Check out SPFx Upload File to SharePoint Document Library With Metadata

Add Button to Custom Webpart in SPFX to Create SharePoint List

Here, we are going to add a button control to the SPFx client-side webpart. When the user clicks this button, it calls the custom function we have covered above. That function will start running and perform actions like creating the SharePoint list, updating the list name, adding columns, etc.

Update your code’s render() method with the below code in the .ts file.

  public render(): void {
    this.domElement.innerHTML = `
    <section class="${styles.createSpListwithColumns} ${!!this.context.sdks.microsoftTeams ? styles.teams : ''}">
      <div>
        <h3>Welcome to SharePoint Framework Webaprt! Click on the button below to create SharePoint list along with columns</h3>
        <button id="createListButton">Employee Details</button>
      </div>
    </section>`;
    this.attachButtonEvent();
  }

Here,

  • <button> </button> = This HTML element will create the button control with the id createListButton
  • this.attachButtonEvent() = It calls the attachButtonEvent() function. It returns an error until you provide the code below under the render() method.
  private attachButtonEvent(): void {
    const createListButton = this.domElement.querySelector("#createListButton");

    if (createListButton) {
      createListButton.addEventListener("click", this.createListAndColumns.bind(this));
    }
  }

Here:

  • createListButton = Reteive the button control by passing the button ID in the domElement.querySelector()
  • If the button is present, we add the addEventListener(). So, this event listener is taking the click action and calling the createListAndColumns() method.

So, whenever the user clicks the button control in the SharePoint webpart, immediately it will the function that creates a SharePoint list and adds columns, etc.,

SPFx create sharepoint list with columns

So here is the final code, which creates a SharePoint list along with columns using the pnp js library in SPFX:

import { Version } from '@microsoft/sp-core-library';
import {type IPropertyPaneConfiguration,PropertyPaneTextField} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import styles from './CreateSpListwithColumnsWebPart.module.scss';
import * as strings from 'CreateSpListwithColumnsWebPartStrings';
import { spfi, SPFx } from "@pnp/sp";
import { FieldTypes } from "@pnp/sp/fields/types";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/fields";
import "@pnp/sp/views";
import "@pnp/sp/navigation";

export interface ICreateSpListwithColumnsWebPartProps {
  description: string;
}

export default class CreateSpListwithColumnsWebPart extends BaseClientSideWebPart<ICreateSpListwithColumnsWebPartProps> {
  private sp: ReturnType<typeof spfi>;
  public render(): void {
    this.domElement.innerHTML = `
    <section class="${styles.createSpListwithColumns} ${!!this.context.sdks.microsoftTeams ? styles.teams : ''}">
      <div>
        <h3>Welcome to SharePoint Framework Webaprt! Click on the button below to create SharePoint list along with columns</h3>
        <button id="createListButton">Employee Details</button>
      </div>
    </section>`;
    this.attachButtonEvent();
  }
  private attachButtonEvent(): void {
    const createListButton = this.domElement.querySelector("#createListButton");

    if (createListButton) {
      createListButton.addEventListener("click", this.createListAndColumns.bind(this));
    }
  }
  
  private async createListAndColumns(): Promise<void> {
    try {
      const internalListName = "EmployeeDetails";
      const displayListName = "Employee Details";

      // Create SharePoint list with internal name
      const createdList = await this.sp.web.lists.add(internalListName, displayListName, 100);

      //get List id
      const listId = createdList.Id;

      //update library internal name with display name.
      await this.sp.web.lists.getById(listId).update({ Title: displayListName });

      // Add to Quick Launch with the correct URL format for document libraries
      const listUrl = `./Lists/${internalListName}/AllItems.aspx`;  //url of list    
      await this.sp.web.navigation.quicklaunch.add(displayListName, listUrl , true);

      // Columns to add stored in library.
      const listTitle = displayListName;
      const columns = [
            { name: "EmployeeID", type: FieldTypes.Text, title: "Employee ID" },
            { name: "PhoneNumber", type: FieldTypes.Number, title: "Phone Number" },
            { name: "Address", type: FieldTypes.Note, title: "Address" },
            { name: "IsFresher", type: FieldTypes.Boolean, title: "Is Fresher" },
            { name: "Department", type: FieldTypes.Choice, title: "Department", choices: ["HR", "IT", "Marketing", "Sales", "Finance", "Research"] },
            { name: "JoiningDate", type: FieldTypes.DateTime, title: "Joining Date" },
            { name: "ProfileImage", type: FieldTypes.Image, title: "Profile Image" },
            { name: "Manager", type: FieldTypes.User, title: "Manager" }
        ];

    // Iterating over columns to add fields
    for (const column of columns) {
          if (column.type === FieldTypes.Choice) {
            await this.sp.web.lists.getByTitle(listTitle).fields.addChoice(column.name, {
              Group: "Custom Columns",
              Description: column.title,
              Required: false,
              Choices: column.choices || [],
             });
        } else {
          await this.sp.web.lists.getByTitle(listTitle).fields.add(column.name, column.type, {
          Group: "Custom Columns",
          Description: column.title,
          Required: false,
    });
  }
  // Update column display name after creation
  await this.sp.web.lists.getByTitle(listTitle).fields.getByInternalNameOrTitle(column.name).update({ Title: column.title });

    // Renaming the default Title field to "Country Name"
    const titleField = await this.sp.web.lists.getByTitle(displayListName).fields.getByInternalNameOrTitle('Title');
    await titleField.update({Title: "Employee Full Name"});


  // Add to the default view
  await this.sp.web.lists.getByTitle(listTitle).defaultView.fields.add(column.name);
}
      alert("Employee Details List and its columns created successfully!");
    } catch (error) {
      console.error("Error creating library or columns:", error);
      alert("Error creating list or columns. Please check the console.");
    }
  }


  protected async onInit(): Promise<void> {
    this.sp = spfi().using(SPFx(this.context));
  }

  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
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

Save the changes and run the below command in the TEMINAL. Then, it will redirect to the SharePoint workbench site there. You can see this web part. Click on the button control and check on the SharePoint site; the list will be created along with columns like in the image below.

gulp serve
spfx webpart to create sharepoint lists

I hope you understand creating a SharePoint list in SPFx using the PnP Js library. I have covered all the topics related to the SharePoint list and columns in this article. This includes updating the SharePoint list name to make it visible on the SharePoint Online site’s quick launch bar.

I also explain how to create different types of columns within a SharePoint list, rename the title field, and update field names. Lastly, I guide you through adding these fields to the default view of the SharePoint list.

All of these actions can be completed with a single button click on the SharePoint site’s custom web part. You can download this spfx solution over here, and if you face any issues, you can contact us.

Create a SharePoint List using Rest API in SharePoint Framework

Now, we will see how to create a list using the SharePoint Framework (SPFx) and TypeScript.

So, let us first create the SPFx solution.

Step 1: To Create a new Solution, for example, “CheckListExists

Open the Nodejs command prompt. Create a directory for the SPFx solution.

md CheckListExists

Navigate to the directory created above.

 cd CheckListExists

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

yo @microsoft/sharepoint

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

  • Solution Name: Hit Enter to have a default name (CheckListExists 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 On-premise (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. Selected choice – N (install on each site explicitly)
  • Type of client-side component to create: We can choose to create a client-side web part or an extension. Choose the web part option. Select option – Web-part.
  • Web part name: Hit enter to select the default name or type in any other name. Type name – checkListExists
  • 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

At this point, Yeoman installs the required dependencies and scaffolds the solution files along with the checkListExists web part. This might take a few minutes.

When the scaffold is complete, you should get a Successful message.

Step 3: In the same command prompt, type the below command to open the solution in the Visual Studio code editor -> ” code .

Create CustomList using spfx

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

Here, we have used Rest API to create a SharePoint list inside the code in SharePoint Framework.

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 './CheckListExistsWebPart.module.scss';
import * as strings from 'CheckListExistsWebPartStrings';
import { SPHttpClient, 
  SPHttpClientResponse,
  ISPHttpClientOptions
} from '@microsoft/sp-http';

export interface ICheckListExistsWebPartProps {
  description: string;
}

export default class CheckListExistsWebPart extends BaseClientSideWebPart<ICheckListExistsWebPartProps> {
  
  private createSharePointList(): void {
    const getListUrl: string = this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('My List')";
    this.context.spHttpClient.get(getListUrl, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
    if (response.status === 200) {
    alert("List already exists.");
    return; // list already exists
    }
    if (response.status === 404) {
    const url: string = this.context.pageContext.web.absoluteUrl + "/_api/web/lists";
    const listDefinition : any = {
    "Title": "My List",
    "Description": "My description",
    "AllowContentTypes": true,
    "BaseTemplate": 100,
    "ContentTypesEnabled": true,
    };
    const spHttpClientOptions: ISPHttpClientOptions = {
    "body": JSON.stringify(listDefinition)
    };
    this.context.spHttpClient.post(url, SPHttpClient.configurations.v1, spHttpClientOptions)
    .then((response: SPHttpClientResponse) => {
    if (response.status === 201) {
    alert("List created successfully");
    } else {
    alert("Response status "+response.status+" - "+response.statusText);
    }
    });
    } else {
    alert("Something went wrong. "+response.status+" "+response.statusText);
    }
    });
    }
  public render(): void {
    this.domElement.innerHTML =
    `<div>
    <button type='button' class='ms-Button'>
    <span class='ms-Button-label'>Create List</span>
    </button>
    </div>`;
    this.createSharePointList = this.createSharePointList.bind(this);
    const button: HTMLButtonElement = this.domElement.getElementsByTagName("BUTTON")[0] as HTMLButtonElement;
    button.addEventListener("click", this.createSharePointList);
  }
  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
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

Step 5: In the command prompt, type “gulp serve,” which will be the local workbench.

While the SharePoint local workbench is running, open the SharePoint workbench by typing a URL like below:

https://<domain-name>.SharePoint.com/sites/<SiteName>/_layouts/15/workbench.aspx

Example:
https://tsinfo.SharePoint.com/sites/HR/_layouts/15/workbench.aspx

Step 6: In the SharePoint workbench page, add the web part “CheckListExists.” Then, it will show the “Create List” Button.

create list using sharepoint framework

Step 7: When a user clicks on the Create List button, it will check if the list with the same Title exists, then it will show an alert message “List already exists” like below:

create sharepoint list using spfx

Step 8: If the list does not exist with the name “My List” in the SharePoint site, then a new SharePoint list will be created with the name “My List” in the SharePoint site.

create sharepoint list spfx

This is how to create a SharePoint list in SharePoint Framework (SPFx) in SharePoint Online. It will also check if the SharePoint list already exists before creating the SharePoint Online list.

Also, you may like:

4 thoughts on “Create a SharePoint List using SharePoint Framework [Including Adding Columns]”

  1. First of all, thank you for the article, it helped a lot. Is there a way to add the “Add to website navigation” here too?
    Like a keyword to add in the definition and set to true / false depending on the checkbox (just like in the standard SharePoint create list dialog)?

    const listDefinition : any = {
    “Title”: “My List”,
    “Description”: “My description”,
    “AllowContentTypes”: true,
    “BaseTemplate”: 100,
    “ContentTypesEnabled”: true,
    “???”: this.state.addListToWebsiteNavigation
    };

    Thanks in advance!

Leave a Comment

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App