SharePoint framework crud operations no javascript framework

Let us check out an example on SharePoint framework crud operations no JavaScript framework. This is crud operations in spfx example using PnP.

I have also created a complete video tutorial on crud operations using sharepoint framework and you can watch it on YouTube.

In this spfx crud operations using PnP tutorial we will see:

  • How to create the SPFx client-side web part for CRUD operations
  • Display SharePoint list item using the SharePoint framework
  • Insert/Add item to SharePoint list using SharePoint framework
  • Update a list item using the SharePoint framework
  • Delete a SharePoint list item using SPFx

Also, you can download the Spfx crud operations using pnp project so that you can run the project and see the output.

Note: You can also check out the SharePoint Framework premium training course to learn more about the SPFx development.

SharePoint framework crud operations

For this SharePoint framework crud operations example, I have created a SharePoint Online list having the below columns.

  • ProjectName (Single line text)
  • CompletationStatus (Yes/No field)
  • Technology (Choice column) having values as SharePoint, PowerBI, PowerApps, Power Automate, SPFx, ReactJS)

The SharePoint list having some data looks like below:

sharepoint framework crud operations no javascript framework
sharepoint framework crud operations no javascript framework

If you want to do the same crud operations in spfx example, then create a SharePoint Online list like above.

Once you will use crud operation in spfx code, you will see an output like below:

spfx crud operations using pnp
spfx crud operations using pnp

So let us start.

If you are new to SharePoint framework, then we need to do the set up the SharePoint framework development environment. You can follow the below articles:

CRUD operations in sharepoint framework – Create the SPFx Project

So first, let us create the SharePoint framework client-side web parts to do the CRUD operations SPFx example.

Open Node.js command prompt in administrator mode. You can also use windows command prompt, PowerShell command prompts. The run the below command:

md CRUD6

cd CRUD6

After this run the below command:

yo @microsoft/sharepoint
sharepoint framework no javascript
sharepoint framework no javascript

Now, it will ask you a few details like below:

  • What is your solution name? Click enter to take the default value.
  • Which baseline packages do you want to target for your component(s). You can choose from the below options
    • SharePoint Online Only (latest)
    • SharePoint 2016 onwards, including 2019 and SharePoint Online
    • SharePoint 2019 onwards, including SharePoint Online
  • Press Enter to choose the default one (SharePoint Online Only (latest).
  • Where do you want to place the files?
    • Use the current folder
    • Create a subfolder with solution name, press enter to use the first option.
  • 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? Type N.
  • Will the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant. Type N.
  • Which type of client-side component to create?
    • WebPart
    • Extension
    • Library
  • Here choose WebPart.
crud operations in sharepoint framework
crud operations in sharepoint framework

Next, it will ask you about the web part details.

  • What is your web part name? HelloWorld Click Enter
  • What is your Web part description? HelloWorld description Click Enter
  • Which framework would you like to use? Select No JavaScript framework from the below options:
    • No JavaScript framework
    • React
    • Knockout
crud operations using sharepoint framework and pnp js library
crud operations using sharepoint framework and pnp js library

Then it will take some time and the SPFx solution will get created and you will see a successful message like below:

crud operations with sharepoint framework client-side web parts
crud operations with sharepoint framework client-side web parts

Since, we are going to use here jQuery and PnP, run the below commands one by one.

npm install jquery --save

npm i @pnp/sp

Once the above commands run successfully, type the below command to open the solution using visual studio code.

code .

The spfx crud operations solution looks like below:

crud operations using sharepoint framework
crud operations using sharepoint framework

Open the src/webparts\helloworld/HelloWorldWebPart.ts file and write the import statements.

import { sp, Web, IWeb } from "@pnp/sp/presets/all";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import * as $ from 'jquery';

CRUD operations using SharePoint framework – Display All Items from SharePoint List

The first thing we will do in the CRUD operations using SharePoint framework solution is to display all the items from the SharePoint list and we will use here the PnP code.

When the web part added to the page, by default it will display the list items in a tabular format.

And also it will bind the choices from the SharePoint list Technology column.

Below is the code.

Note: I will suggest to either download the project or check below for the complete code.

Here, you can also see, we have added the html buttons and html tables.

var technologyChoices;
    technologyChoices = await getChoiceFields(this.context.pageContext.web.absoluteUrl);

this.domElement.innerHTML = `
        ${await this.getHTML()}
        `;

public async getHTML() {
    let web = Web(this.context.pageContext.web.absoluteUrl);
    const items: any[] = await web.lists.getByTitle("ProjectDetails").items.getAll();
    console.log(items);
    return this.domElement.innerHTML = `<div>
        <h1>CRUD with No Javascript</h1>
        <table class="${styles.table}">
      <thead>
        <tr>
          <th></th>
          <th>Project Name</th>
          <th>Completion Status</th>
          <th>Technology</th>
        </tr>
      </thead>
      <tbody>
        ${items && items.map((item, i) => {
      return [
        "<tr id=UpdateDeleteItem class=UpdateDeleteItem>" +
        "<td><input type=radio id=" + item.ID + " name=itemID value=" + item.ID + "></td>" +
        "<td>" + item.ProjectName + "</td>" +
        "<td>" + checkStatus(item.CompletionStatus) + "</td>" +
        "<td>" + item.Technology + "</td>" +
        "</tr>"
      ];
    })}
      </tbody>

    </table>
    <form>

        <button class="${styles.button}" type="button" id="Create">Create</button>
        <button class="${styles.button}" type="button" id="Update">Update</button>
        <button class="${styles.button}" type="button" id="Delete">Delete</button>
        <br><br>

        <label class="${styles.label}" for="projectname">Project Name:</label>
        <input class="${styles.borderset}" type="text" id="projectname" name="projectname"><br><br>
        <label class="${styles.label}" for="completionstatus">Completion Status:</label>
        <input class="${styles.borderset}" type="radio" id="completed" name="completed" value="completed">
        <label for="completed">Completed</label><br><br>
        <label class="${styles.label}" for="technology">Technology:</label>
<select class="${styles.borderset}" name="technology" id="technology" form="technologyform">
${technologyChoices.map((item) => {
      return [
        `<option value='${item.key}'>${item.value}</option>`
      ];
    })}
  
  </select><br><br></form>
  </div>`;

  }


export const getChoiceFields = async (webURL) => {
  let resultarr = [];
  await fetch(webURL + "/_api/web/lists/GetByTitle('ProjectDetails')/fields?$filter=EntityPropertyName eq 'Technology'", {
    method: 'GET',
    mode: 'cors',
    credentials: 'same-origin',
    headers: new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Cache-Control': 'no-cache',
      'pragma': 'no-cache',
    }),
  }).then(async (response) => await response.json())
    .then(async (data) => {
      for (var i = 0; i < data.value[0].Choices.length; i++) {
        //for(var j=0;j<=i;j++)
        //{
        await resultarr.push({
          key: data.value[0].Choices[i],
          value: data.value[0].Choices[i]
          //key:data.value[i].Choices[j],
          //text:data.value[i].Choices[j]
        });
        //}
      }
    });
  return await resultarr;
};

export const checkStatus = (value): string => {

  if (value) {
    return 'Completed';
  }
  else {
    return 'In Progress';
  }
};

SPFx crud operations: Insert item to SharePoint list

In the next we will see how to insert item to SharePoint list. Below is the code:

var create = document.getElementById('Create');
    create.addEventListener('click', async function () {
      // var e = document.getElementById("technology");
      //var strUser = e.options[e.selectedIndex].text;  
      await web.lists.getByTitle("ProjectDetails").items.add({

        ProjectName: $("#projectname").val(),
        CompletionStatus: $("#completed:checked").val() == "completed" ? true : false,
        Technology: $("#technology :selected").text()

      }).then(i => {
        console.log(i);
      });
      alert("Created Successfully");
      await currentobj.render();
      $("#projectname").val("");
      $("#completed").prop('checked', false);
      $("#technology").val("");

    });

SPFx crud operations using no javascript: Update List Item

Now, let us see how to do an update item operation in SPFx.

To update an item, first select the item from the HTML table and then it will populate the existing values. Then you can change the value and click on the Update button.

The SharePoint list item will be updated and then it will reload the HTML table with the list data.

var UpdateDeleteItem = document.getElementById('UpdateDeleteItem');
    UpdateDeleteItem.addEventListener('click', async function () {
      let id:number=Number($('input[name="itemID"]:checked').val());
      const item: any[] = await web.lists.getByTitle("ProjectDetails").items.getById(id).get();
      console.log(item);

      $("#projectname").val(item["ProjectName"]);
      $("#completed").prop('checked', item["CompletionStatus"]);
      $("#technology").val(item["Technology"]);
    });

    $('input[name*="itemID"]').on('change', async function () {
      let id:number=Number($('input[name="itemID"]:checked').val());
      const item: any[] = await web.lists.getByTitle("ProjectDetails").items.getById(id).get();
      console.log(item);

      $("#projectname").val(item["ProjectName"]);
      $("#completed").prop('checked', item["CompletionStatus"]);
      $("#technology").val(item["Technology"]);
    });


var update = document.getElementById('Update');
    update.addEventListener('click', async function () {
      // var e = document.getElementById("technology");
      //var strUser = e.options[e.selectedIndex].text;
      let id:number=Number($('input[name="itemID"]:checked').val());
      await web.lists.getByTitle("ProjectDetails").items.getById(id).update({
        ProjectName: $("#projectname").val(),
        CompletionStatus: $("#completed:checked").val() == "completed" ? true : false,
        Technology: $("#technology :selected").text()

      }).then(i => {
        console.log(i);
      });
      alert("Updated Successfully");
      await currentobj.render();
      $("#projectname").val("");
      $("#completed").prop('checked', false);
      $("#technology").val("");
    });

SPFx crud operations using pnp: Delete SharePoint list

Now in the next spfx crud example, we will see how to delete the SharePoint list item using SharePoint framework.

var deletedata = document.getElementById('Delete');
    deletedata.addEventListener('click', async function () {
      // var e = document.getElementById("technology");
      //var strUser = e.options[e.selectedIndex].text;  
      let id:number=Number($('input[name="itemID"]:checked').val());
      await web.lists.getByTitle("ProjectDetails").items.getById(id).delete()
        .then(i => {
          console.log(i);
        });
      alert("Deleted Successfully");
      await currentobj.render();
      $("#projectname").val("");
      $("#completed").prop('checked', false);
      $("#technology").val("");
    });

CRUD operations in sharepoint framework: Complete Code

Below is the complete SPFx CRUD operations code:

import { Version } from '@microsoft/sp-core-library';
import {
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import * as $ from 'jquery';
import styles from './HelloWorldWebPart.module.scss';
import * as strings from 'HelloWorldWebPartStrings';
import { sp, Web, IWeb } from "@pnp/sp/presets/all";
import "@pnp/sp/lists";
import "@pnp/sp/items";

var technologyChoices;
export interface IHelloWorldWebPartProps {
  description: string;
}

export default class HelloWorldWebPart extends BaseClientSideWebPart <IHelloWorldWebPartProps> {

  public async render(): Promise<void> {
    var currentobj = this;
    technologyChoices = await getChoiceFields(this.context.pageContext.web.absoluteUrl);
    let web = Web(this.context.pageContext.web.absoluteUrl);
    const items: any[] = await web.lists.getByTitle("ProjectDetails").items.getAll();
    console.log(items);
    this.domElement.innerHTML = `
        ${await this.getHTML()}
        `;
    var create = document.getElementById('Create');
    create.addEventListener('click', async function () {
      // var e = document.getElementById("technology");
      //var strUser = e.options[e.selectedIndex].text;  
      await web.lists.getByTitle("ProjectDetails").items.add({

        ProjectName: $("#projectname").val(),
        CompletionStatus: $("#completed:checked").val() == "completed" ? true : false,
        Technology: $("#technology :selected").text()

      }).then(i => {
        console.log(i);
      });
      alert("Created Successfully");
      await currentobj.render();
      $("#projectname").val("");
      $("#completed").prop('checked', false);
      $("#technology").val("");

    });

    var update = document.getElementById('Update');
    update.addEventListener('click', async function () {
      // var e = document.getElementById("technology");
      //var strUser = e.options[e.selectedIndex].text;
      let id:number=Number($('input[name="itemID"]:checked').val());
      await web.lists.getByTitle("ProjectDetails").items.getById(id).update({
        ProjectName: $("#projectname").val(),
        CompletionStatus: $("#completed:checked").val() == "completed" ? true : false,
        Technology: $("#technology :selected").text()

      }).then(i => {
        console.log(i);
      });
      alert("Updated Successfully");
      await currentobj.render();
      $("#projectname").val("");
      $("#completed").prop('checked', false);
      $("#technology").val("");
    });

    var deletedata = document.getElementById('Delete');
    deletedata.addEventListener('click', async function () {
      // var e = document.getElementById("technology");
      //var strUser = e.options[e.selectedIndex].text;  
      let id:number=Number($('input[name="itemID"]:checked').val());
      await web.lists.getByTitle("ProjectDetails").items.getById(id).delete()
        .then(i => {
          console.log(i);
        });
      alert("Deleted Successfully");
      await currentobj.render();
      $("#projectname").val("");
      $("#completed").prop('checked', false);
      $("#technology").val("");
    });

    var UpdateDeleteItem = document.getElementById('UpdateDeleteItem');
    UpdateDeleteItem.addEventListener('click', async function () {
      let id:number=Number($('input[name="itemID"]:checked').val());
      const item: any[] = await web.lists.getByTitle("ProjectDetails").items.getById(id).get();
      console.log(item);

      $("#projectname").val(item["ProjectName"]);
      $("#completed").prop('checked', item["CompletionStatus"]);
      $("#technology").val(item["Technology"]);
    });

    $('input[name*="itemID"]').on('change', async function () {
      let id:number=Number($('input[name="itemID"]:checked').val());
      const item: any[] = await web.lists.getByTitle("ProjectDetails").items.getById(id).get();
      console.log(item);

      $("#projectname").val(item["ProjectName"]);
      $("#completed").prop('checked', item["CompletionStatus"]);
      $("#technology").val(item["Technology"]);
    });

  }
  public async getHTML() {
    let web = Web(this.context.pageContext.web.absoluteUrl);
    const items: any[] = await web.lists.getByTitle("ProjectDetails").items.getAll();
    console.log(items);
    return this.domElement.innerHTML = `<div>
        <h1>CRUD with No Javascript</h1>
        <table class="${styles.table}">
      <thead>
        <tr>
          <th></th>
          <th>Project Name</th>
          <th>Completion Status</th>
          <th>Technology</th>
        </tr>
      </thead>
      <tbody>
        ${items && items.map((item, i) => {
      return [
        "<tr id=UpdateDeleteItem class=UpdateDeleteItem>" +
        "<td><input type=radio id=" + item.ID + " name=itemID value=" + item.ID + "></td>" +
        "<td>" + item.ProjectName + "</td>" +
        "<td>" + checkStatus(item.CompletionStatus) + "</td>" +
        "<td>" + item.Technology + "</td>" +
        "</tr>"
      ];
    })}
      </tbody>

    </table>
    <form>

        <button class="${styles.button}" type="button" id="Create">Create</button>
        <button class="${styles.button}" type="button" id="Update">Update</button>
        <button class="${styles.button}" type="button" id="Delete">Delete</button>
        <br><br>

        <label class="${styles.label}" for="projectname">Project Name:</label>
        <input class="${styles.borderset}" type="text" id="projectname" name="projectname"><br><br>
        <label class="${styles.label}" for="completionstatus">Completion Status:</label>
        <input class="${styles.borderset}" type="radio" id="completed" name="completed" value="completed">
        <label for="completed">Completed</label><br><br>
        <label class="${styles.label}" for="technology">Technology:</label>
<select class="${styles.borderset}" name="technology" id="technology" form="technologyform">
${technologyChoices.map((item) => {
      return [
        `<option value='${item.key}'>${item.value}</option>`
      ];
    })}
  
  </select><br><br></form>
  </div>`;

  }

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

export const getChoiceFields = async (webURL) => {
  let resultarr = [];
  await fetch(webURL + "/_api/web/lists/GetByTitle('ProjectDetails')/fields?$filter=EntityPropertyName eq 'Technology'", {
    method: 'GET',
    mode: 'cors',
    credentials: 'same-origin',
    headers: new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Cache-Control': 'no-cache',
      'pragma': 'no-cache',
    }),
  }).then(async (response) => await response.json())
    .then(async (data) => {
      for (var i = 0; i < data.value[0].Choices.length; i++) {
        //for(var j=0;j<=i;j++)
        //{
        await resultarr.push({
          key: data.value[0].Choices[i],
          value: data.value[0].Choices[i]
          //key:data.value[i].Choices[j],
          //text:data.value[i].Choices[j]
        });
        //}
      }
    });
  return await resultarr;
};
export const checkStatus = (value): string => {

  if (value) {
    return 'Completed';
  }
  else {
    return 'In Progress';
  }
};

And also you can add the scss code for styling of the HTML table code. You can add in the end.

.table {
  border: 3px solid black;
  border-collapse: collapse;
  width: 100%;
  margin-top: -6px;
}

.table th, td {
  border: 1px solid black;
  border-collapse: collapse;
  padding: 10px;
  text-align: center;
}

.table tr:nth-child(even) {
  background-color: #dddddd;
}

.button
{
    background: #c5bea0;
    border: 1px solid blck;
    width: 100px;
    height: 28px;
    margin: 18px;
    font-weight: 700;
}

.label {
  font-weight: 700;
  margin: 0 4px;
  vertical-align: top;
  display: inline-block;
}

.borderset{
  border: 1px solid black;
}

Once the code is ready, you can run the below command to run the SPFx solution locally.

gulp serve

This will open the local workbench. While the local workbench is running, open the SharePoint workbench and make sure the list should be there in the list.

In the SharePoint Online site work bench, add the HelloWorld web part and it will appear like below:

crud operations in spfx
crud operations in spfx

If you want to deploy the crud operations with sharepoint framework client-side web parts to SharePoint Online App catalog or site collection app catalog in SharePoint Online, then we need to create the .sppkg file by running the below command:

gulp bundle --ship

gulp package-solution --ship

Once you run the above commands, it will create the .sppkg file in the sharepoint\solution folder.

Download Complete spfx crud operations using no javascript project or solution

Click on this spfx pnp crud operations link to download the complete project.

Once the project downloaded completely, unzip the project and then run the below commands

npm i

npm install jquery --save

npm i @pnp/sp

gulp server

Now, you can use the crud operations with sharepoint framework client-side web parts.

crud operations in sharepoint framework – Video tutorial

I have also created a complete video tutorial on crud operations in sharepoint framework. Watch the complete video tutorial below:

You may like the following SPFx tutorials:

In this SPFx tutorial, we learned on crud operations using sharepoint framework and pnp js library. I hope you liked the sharepoint framework crud operations no javascript framework example.

  • >