Create Folders and Subfolders in SharePoint document library using SPFx

Recently, we got a requirement from a client to create folders and subfolders in a SharePoint Online document library using SharePoint Framework (SPFx). We can do this using the PnP js library in an SPFx project. In this tutorial, I will explain, step by step, how to create folders and subfolders in a SharePoint document library using SPFx.

Add Folders and SubFolders to SharePoint Document Library using SPFx

Here, we will create a client-side web part using the SharePoint framework that contains a button. When a user clicks on the button, it will check if the folder exists or not; if it does not exist, it will create the folders and subfolders in the SharePoint Online document library.

You can also look at the example below when I click the button control on the SharePoint custom web part. It displays an alert message like folders and subfolders have been added successfully to the SharePoint document library.

add folder and subfolders in a sharepoint document library with spfx

If you are new to SPFx, I recommend first checking out this tutorial to set up the SPFx development environment.

Follow the steps below to add folders and subfolders to the SharePoint document library using SharePoint Framework.

1. Open any command prompt and add the cmd below to create a folder.

md AddFoldersAndSubFolderToDocumentLibrary

2. To enter into that folder add the command below and click on enter.

cd AddFoldersAndSubFolderToDocumentLibrary

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 below questions. Provide the answers below that I have given.

  • 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? = AddFolderAndSubFolderToDocumentLibrary
  • 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.

Then, open the serve.json file and add your SharePoint site address to the “initialPage” parameter.

create folders and subfolders in sharepoint using spfx

6. After updating the URL, run the code below on the TERMINAL.

gulp serve

7. To add folders to the SharePoint document library, we need to make the REST API calls to SharePoint, so we’re using the PnPjs library. Run the cmd below to install the PnPjs library.

npm install @pnp/sp --save

8. Now, Open the src folder ->Webpart -> AddFoldersAndSubFolderToDocumentLibrary.ts file -> Provide the below import commands.

import { spfi, SPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/folders";

Add this variable in the export default class structure>

private sp: ReturnType<typeof spfi>;

It creates an object with the spfi.

SharePoint REST API create folder if not exists

9. Then, update the OnInit() method with the code below.

  protected async onInit(): Promise<void> {
    this.sp = spfi().using(SPFx(this.context));
  }
add folders and subfolders to sharepoint library using spfx with pnp js library

11. Add the below code under the export default class structure.

  private async AddFoldersandSubFolders(): Promise<void> {
    try {
        const LibraryName = "Employee Approved Claims".replace(/\s+/g, ""); // Remove spaces
        const siteUrl = this.sp.web.toUrl().replace(/\s+/g, ""); // Remove spaces

        console.log("Site URL: ", siteUrl);

        // Define folders and their subfolders
        const foldersWithSubfolders: { [key: string]: string[] } = {
            "Employee Travel": ["Transportation", "Accommodation"],
            "Policy Violations": ["Duplicate Submissions", "Manager Review"],
            "Reports": ["Manager Review", "Finance Review"],
            "Non-Reimbursable Items": [],
        };

        // Construct library folder path correctly
        const libraryFolderPath = `${LibraryName}`; 

        // Create main folders and their subfolders
        for (const folderName in foldersWithSubfolders) {
            if (foldersWithSubfolders.hasOwnProperty(folderName)) {
                const subfolders = foldersWithSubfolders[folderName];

                // Remove spaces from folder names
                const cleanedFolderName = folderName.replace(/\s+/g, "");

                const mainFolderPath = `${libraryFolderPath}/${cleanedFolderName}`;
                console.log(`Creating main folder: ${mainFolderPath}`);

                // Create main folder
                await this.sp.web.folders.addUsingPath(mainFolderPath);

                // Create subfolders inside the main folder
                for (const subfolder of subfolders) {
                    const cleanedSubfolder = subfolder.replace(/\s+/g, "");
                    const subfolderPath = `${mainFolderPath}/${cleanedSubfolder}`;
                    console.log(`Creating subfolder: ${subfolderPath}`);
                    await this.sp.web.folders.addUsingPath(subfolderPath);
                }
            }
        }
        alert("Folders and subfolders are added successfully!");
    } catch (error) {
        console.error("Error creating folders:", error);
        alert("Error in adding folders. Check the console for details.");
    }
}

Let’s understand the above code:

  • AddFoldersandSubFolders(): A custom function that adds folders and subfolders to the SharePoint document library.
  • siteUrl, LibraryName = These variables store the library name and SharePoint site addresses. We used replace() with a regex to avoid spaces between these names.
  • foldersWithSubfolders = It is a Java script dictionary that contains the folders and subfolders names.
  • Using for loop, we’re iterating over through the dictionary to get the folder names.
  • await this.sp.web.folders.addUsingPath(mainFolderPath); = Using this code, we’re creating main folders in the document library.
  • await this.sp.web.folders.addUsingPath(subfolderPath); = This code creates subfolders within the folders in the SharePoint document library.
  • The alert() function displays a success message if it successfully adds the folders and subfolders. If it fails, then it also displays an error message.
How to create a folder in a document library with spfx

12. To call the above custom function, update the render() method with the below code.

 public render(): void {
    this.domElement.innerHTML = `
    <section class="${styles.addFolderAndSubFolderToDocumentLibrary} ${!!this.context.sdks.microsoftTeams ? styles.teams : ''}">
      <div class="${styles.welcome}">
        <img alt="" src="${this._isDarkTheme ? require('./assets/welcome-dark.png') : require('./assets/welcome-light.png')}" class="${styles.welcomeImage}" />
        <h2>Well done, ${escape(this.context.pageContext.user.displayName)}!</h2>
        <div>${this._environmentMessage}</div>
        <div>Web part property value: <strong>${escape(this.properties.description)}</strong></div>
        <button id="createFolder">Add Folders & Subfolders</button>

      </div>       
    </section>`;
    this.attachButtonEvent();
  }
  private attachButtonEvent(): void {
    const createFolderButton = this.domElement.querySelector("#createFolder");
    if (createFolderButton) {
      createFolderButton.addEventListener("click", this.AddFoldersandSubFolders.bind(this));
    }
  }

Within the render(), I added a button control.

  • attachButtonEvent = Custom method that selects the button control using query selector.
  • Using the addEventListener() method, we’re calling the create folders and subfolders function on the click event.
create a folder and subfolders in a document library with spfx

13. Save the changes and provide the below command in the TERMINAL pane.

gulp serve

14. Now, it will launch the workbench site, click on the button on the custom webpart. It will create folders and subfolders on the SharePoint document library.

Create folders and sub-folders in document library with spfx

Conclusion

As an SPFx developer, you might required to create folders and nested subfolders in a SharePoint document library using SPFx. In this tutorial, I explained in detail how to create folders and subfolders in a SharePoint document library using SharePoint Framework with PnPJS library. Along with adding folders and subfolders to the document library, I also explained how to remove unnecessary spaces within the site URL and library names.

You may also like:

>
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

Power Platform Tutorial

FREE Power Platform Tutorial PDF

Download 120 Page FREE PDF on Microsoft Power Platform Tutorial. Learn Now…