Here, we are going to see how to create a new folder under SharePoint List using PnP JavaScript Component.

To know more about this JavaScript library, check the below links

JavaScript Example:

The below steps and code snippets used to create a new folder in SharePoint list using PnP JavaScript library,

  1. Download Required files to use PnP-JS-Core library from the below links and upload that to Site Asstes or Style Library
    • Download pnp.js PnP JS file
    • Download fetch.js Used by PnP js file to handle web requests and responses (Required in IE)
    • Download promise.js Used by PnP js file to handle web requests and responses (Required in IE)
  2. Create new web part page and insert Content Editor web part
  3. Create a sample.html file in Site Assets or Style library and insert the below code snippet

The below example creates a new folder under root level of a SharePoint list or library

<script type="text/javascript" src="/siteassets/scripts/fetch.js"></script>
<script type="text/javascript" src="/siteassets/scripts/promise.min.js"></script> 
<script type="text/javascript" src="/siteassets/scripts/pnp.min.js"></script>
<span id="folderInfo"></span>

<script type="text/javascript">  
//The below example gets the root folder of the Documents library and create a subfolder name as "NewFolderName" under it.
    .add("NewFolderName").then(function(data) {
        document.getElementById("folderInfo").innerHTML = "Folder created successfully.";
    }).catch(function(err) {
        document.getElementById("folderInfo").innerHTML = "Unable to create Folder.";

Typescript Example:

Typescript is the superset of JavaScript and this PnP JS library is developed using the typescript specification. For developing the SharePoint Framework web parts and make the client side development easier, we can vote for typescript. The below is the typescript example for creating a new folder under root folder of the SharePoint List / Library.

import pnp from "sp-pnp-js";

pnp.sp.web.lists.getByTitle("Documents").rootFolder.folders.add("NewFolderName").then(data => {
    this.domElement.querySelector("#folderInfo").innerHTML = "Folder created successfully."
}).catch(err => {
    this.domElement.querySelector("#folderInfo").innerHTML = "Unable to create Folder."