How to get Server Relative URL of List or Library using PnP JS in SPFx webpart

This would be a quick code snippet to get server relative url of list or library using PnP JS in SPFx webpart.  Recently I was working on sample webpart and used PropertyFieldListPicker control to allow configurable property to select list or library. If you wanted to know on how to use this control, refer this link.

Now problem with ListPicker control is it returns us Guid/s of select list or library. My requirement was to find server relative url of select list and library so that I can use getFolderByServerRelativeUrl()  method to add file to this library. Now this method needs libraries or list relative path. So below is that I did to get library’s server relative path.

I used SP PnP js library module for SPFx webpart.

Install it in your SPFx solution using below command.

npm install @pnp/sp --save

Added import statement in webpartcomponent.tsx file

import { sp } from "@pnp/sp";

Used below snippet on button click

sp.web.lists.getById(this.props.library).select("Title","RootFolder/ServerRelativeUrl").expand("RootFolder").get().then((response)=>{

        //Upload a file to the SharePoint Library
        sp.web.getFolderByServerRelativeUrl(response.RootFolder.ServerRelativeUrl)
        .files.add("mycapturedimage.jpg", arrayBuffer, true)
        .then((data) =>{
            alert( data + "upload successfully!");

        })
        .catch((error) =>{
          alert(error);
        });

});

Please note in above this.props.library hold GUID of Library/List which is initialized by ListPicker control once we configure web part and select particular list or library.

Idea here is to get List properties using get method and then expand RootFolder which has ServerRelativeURL property.

Hope you find information useful…Happy coding…

(Visited 69 times, 1 visits today)