SharePoint Attachments Operations with PnP.js in React


Managing attachments in SharePoint lists is a crucial aspect of many business applications. Whether it’s uploading files, retrieving them, or deleting them, an efficient approach ensures seamless user experience and better performance.

In this article, we’ll explore how to handle SharePoint list attachments using PnP.js, a powerful JavaScript library designed for SharePoint interactions. We’ll implement these operations within a React-based SharePoint Framework (SPFx) solution. Along the way, we’ll cover CRUD (Create, Read, Update, Delete) operations, batching techniques for performance improvements, and a comparison with alternative approaches.


What Are SharePoint Attachments?

SharePoint attachments allow users to associate files with list items, effectively enabling document management within lists. Unlike SharePoint document libraries, which store and manage files separately, list attachments are directly tied to specific items, making them useful for scenarios where documents should stay contextually linked to data entries.

For example, an issue-tracking list might need screenshots as attachments, or an HR recruitment list might store resumes alongside applicant records. Using attachments simplifies document handling without requiring separate libraries.


Why Do We Need Attachment Operations?

Attachments play an essential role in many SharePoint-based solutions, and performing operations like uploading, retrieving, and deleting them programmatically offers numerous benefits:

  • Automated Document Management: Attachments can be managed through workflows, reducing manual tasks like adding and removing files.
  • Seamless User Experience: Users can upload files directly through custom interfaces rather than relying on SharePoint’s built-in UI.
  • Integration with Other Systems: Custom applications often require attachment data to be processed, moved, or analyzed alongside other business logic.
  • Performance Optimization: By implementing techniques like batching, we can minimize API calls, improving system efficiency and responsiveness.

Who Uses SharePoint Attachments?
  • Developers: Building SharePoint-based applications with custom attachment management.
  • Business Analysts: Designing workflows and automation solutions that incorporate attachments.
  • IT Administrators: Managing document-heavy SharePoint environments.
  • End Users: Uploading and accessing attachments in SharePoint-powered applications, such as forms or ticketing systems.

Applications That Use SharePoint Attachments
  • HR and Recruitment Systems: Store resumes, offer letters, and employee documentation directly within SharePoint lists.
  • Help Desk and Ticketing Systems: Attach images, logs, or reports to support tickets for better tracking.
  • Project Management Tools: Associate project-related documents with tasks or milestones.
  • CRM and Sales Solutions: Maintain customer-related documents, contracts, and agreements.

CRUD Operations for SharePoint Attachments with PnP.js in React

Let’s explore how we can handle Create, Read, Update, and Delete (CRUD) operations on SharePoint list attachments using PnP.js in a React-based SPFx solution.

1. Create (Upload) Attachments

Uploading an attachment involves selecting a file and adding it to an existing SharePoint list item. The PnP.js method attachmentFiles.add makes this easy.

React Component for File Upload
import { sp } from "@pnp/sp/presets/all";
import { useState } from "react";

const UploadAttachment = ({ listTitle, itemId }) => {
    const [file, setFile] = useState(null);

    const handleFileChange = (event) => {
        setFile(event.target.files[0]);
    };

    const uploadFile = async () => {
        if (file) {
            await sp.web.lists.getByTitle(listTitle)
                .items.getById(itemId)
                .attachmentFiles.add(file.name, file);
            alert("File uploaded successfully");
        }
    };

    return (
        <div>
            <input type="file" onChange={handleFileChange} />
            <button onClick={uploadFile}>Upload</button>
        </div>
    );
};

export default UploadAttachment;
2. Read (Retrieve) Attachments

To display existing attachments, we retrieve their URLs and render them as clickable links.

const getAttachments = async (listTitle, itemId) => {
    const attachments = await sp.web.lists.getByTitle(listTitle)
        .items.getById(itemId)
        .attachmentFiles();
    console.log(attachments);
};
3. Delete Attachments

Removing an attachment from a SharePoint list item is straightforward using PnP.js.

const deleteAttachment = async (listTitle, itemId, fileName) => {
    await sp.web.lists.getByTitle(listTitle)
        .items.getById(itemId)
        .attachmentFiles.getByName(fileName).delete();
    alert("Attachment deleted");
};
Batching Attachments for Performance Optimization

Batching reduces the number of API calls when performing multiple operations, significantly improving performance and reducing latency.

const batchUploadAttachments = async (listTitle, itemId, files) => {
    const batch = sp.web.createBatch();
    
    files.forEach(file => {
        sp.web.lists.getByTitle(listTitle)
            .items.getById(itemId)
            .attachmentFiles.add(file.name, file)
            .inBatch(batch);
    });

    await batch.execute();
    alert("Batch upload completed");
};

Pros and Cons of Using PnP.js for Attachment Management
✅ Pros
  • Simplifies API interactions by providing easy-to-use methods for attachment operations.
  • Reduces code complexity compared to manually handling REST API requests.
  • Supports batching to improve performance and reduce network calls.
  • Integrates seamlessly within SharePoint Framework (SPFx) applications.
❌ Cons
  • Requires SPFx environment, meaning it cannot be used in standalone web applications without SharePoint.
  • Dependency on PnP.js, which may require additional maintenance as SharePoint evolves.
  • Limited offline capabilities, as it relies on live API interactions with SharePoint.

Comparison with Alternative Approaches
ApproachProsCons
PnP.js with ReactOptimized for SPFx, clean API, supports batchingRequires dependency on PnP.js
JavaScript REST APINo external dependenciesVerbose, requires manual request handling
Power AutomateNo-code solution, easy for business usersLimited customization and performance tuning
CSOM (C#)Full SharePoint integration, robustRequires server-side execution, not suitable for SPFx solutions

Managing SharePoint list attachments using PnP.js in React offers a clean, efficient, and scalable approach. Compared to direct REST API calls, PnP.js simplifies operations while providing powerful capabilities like batching. While it introduces an external dependency, its ease of use and efficiency make it an excellent choice for SPFx solutions.

If you’re working with SharePoint attachments, PnP.js is a game-changer. What’s your preferred approach for handling SharePoint attachments? Let us know in the comments!


Audits Connect Content Type CopyFiles CSS Flows GetAllItems Graph GULP Hillbilly Tabs Javascript jQuery Myths Node NodeJs O365 OneDrive Permissions PnP PnPJS Power Automate PowerAutomate PowerShell Pwermissions React ReactJs Recycle Rest API Rest Endpoint Send an HTTP Request to SharePoint SharePoint SharePoint List Extension SharePoint Lists SharePoint Modern SharePoint Online SharePoint Tabs ShellScript SPFX SPO Sync Tags Taxonomy Termstore Versioning VueJS

Leave a Comment

Your email address will not be published. Required fields are marked *