Complete CRUD Example in SPFx Using React and PnPjs

This article will guide you through creating a complete CRUD (Create, Read, Update, Delete) application in SharePoint Framework (SPFx) using React and PnPjs. We’ll build a simple component that allows users to add, view, and delete items from a SharePoint list.

Prerequisites

Before you begin, ensure you have the following:

  • Basic knowledge of React and TypeScript.
  • SPFx development environment set up.
  • PnPjs library installed in your SPFx project.

You can install PnPjs in your project using the following command:

npm install @pnp/sp @pnp/nodejs --save

Component Code: CrudSPFxCompleto.tsx

Here’s the complete code for the CrudSPFxCompleto component:

import * as React from 'react';
import { useState, useEffect } from 'react';
import { SPFI } from '@pnp/sp';
import { IPropsSpBasico } from './IPropsSpBasico';

export interface IListaItems {
  Title: string;
  Id: number;
}

export interface CrudSPFxCompletoProps {
  sp: SPFI; // Getting SP as props
}

const CrudSPFxCompleto: React.FC<CrudSPFxCompletoProps> = ({ sp }) => {
  const [items, setItems] = useState<IListaItems[]>([]);
  const [newItemTitle, setNewItemTitle] = useState('');
  const [loaded, setLoaded] = useState(false);

  // Function to load items from the SharePoint list
  const loadItems = async () => {
    try {
      const listItems: IListaItems[] = await sp.web.lists.getByTitle("ListaExemplo").items();
      setItems(listItems);
      setLoaded(true);
    } catch (error) {
      console.error('Error loading items:', error);
    }
  };

  // Function to add a new item to the SharePoint list
  const addItem = async () => {
    try {
      await sp.web.lists.getByTitle("ListaExemplo").items.add({
        Title: newItemTitle
      });
      setNewItemTitle(''); // Clear the input field
      loadItems(); // Reload items after adding
    } catch (error) {
      console.error('Error adding item:', error);
    }
  };

  // Function to delete an item from the SharePoint list
  const deleteItem = async (id: number) => {
    try {
      await sp.web.lists.getByTitle("ListaExemplo").items.getById(id).delete();
      loadItems(); // Reload items after deletion
    } catch (error) {
      console.error('Error deleting item:', error);
    }
  };

  useEffect(() => {
    loadItems(); // Load items on component mount
  }, []);

  return (
    <div>
      <h1>CRUD SPFx Example</h1>
      <div>
        <input
          type="text"
          value={newItemTitle}
          onChange={(e) => setNewItemTitle(e.target.value)}
          placeholder="New item title"
        />
        <button onClick={addItem}>Add Item</button>
      </div>
      <button onClick={loadItems}>Reload List</button>
      {loaded && (
        <ul>
          {items.map((item) => (
            <li key={item.Id}>
              {item.Title}
              <button onClick={() => deleteItem(item.Id)}>Delete</button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default CrudSPFxCompleto;

Component Breakdown

  1. Imports and Interfaces:
  • We import necessary libraries and define two interfaces: IListaItems for the item structure and CrudSPFxCompletoProps for props.
  1. State Management:
  • We use React’s useState to manage the list of items, the title of the new item, and a loaded flag to track the data loading state.
  1. Loading Items:
  • The loadItems function retrieves items from the SharePoint list called “ListaExemplo” using PnPjs.
  1. Adding Items:
  • The addItem function adds a new item with the title specified in the input field and refreshes the item list.
  1. Deleting Items:
  • The deleteItem function removes an item from the list and reloads the items.
  1. Effect Hook:
  • The useEffect hook is used to load the items when the component mounts.

Usage

To use the CrudSPFxCompleto component, simply pass the sp object as props from your main component:

<CrudSPFxCompleto sp={this.sp} />

Conclusion

You have now created a complete CRUD application in SPFx using React and PnPjs. This example serves as a foundation for building more complex applications in SharePoint.

Further Reading

Edvaldo Guimrães Filho Avatar

Published by

Categories:

Leave a comment