In this article I am showing how to hide and show SPFx webpart content based on user permission.

Step 1: If you are new to SPFx, to create a SPFx webpart refer here

Step 2: Import the page context class in the webpart HideWebpartWebPart.ts file

import { SPPermission } from '@microsoft/sp-page-context';

Step 3: You can check if the user has specific permission via below methods

  • hasAllPermissions : Checks if the user has all the permissions
  • hasAnyPermissions: Checks if the user has any permission from the collection of permissions
  • hasPermission: Checks if the user has given permission
const admin = this.context.pageContext.web.permissions.hasAllPermissions(SPPermission.fullMask);
    const canEdit = this.context.pageContext.web.permissions.hasAnyPermissions(SPPermission.manageWeb);
    const canView = this.context.pageContext.web.permissions.hasPermission(SPPermission.viewPages);

SharePoint has the SPPermission class, you’ll get a variety of permissions, to know more about SPPermission refer here

Step 4: Hide and Show Webpart content, create a css class in “HideWebpartWebPart.module.scss”

.containerhide {
        display: none;
    }

Then verify the user permission and stop load the content based on the user permission. Here I am showing webpart content if user having full permission.

If user have only view permission then not render any content and hide the content div using containerhide css class

Here some sample code

if(admin)
    {
      this.domElement.innerHTML = `
        <div class="${ styles.hideWebpart }">
          <div class="${ styles.container }">
            <div class="${ styles.row }">
              <div class="${ styles.column }">
                <span class="${ styles.title }">Welcome to SharePoint!</span>
                <p class="${ styles.subTitle }">Customize SharePoint experiences using Web Parts.</p>
                <p class="${ styles.description }">${escape(this.properties.description)}</p>
                <p class="${ styles.description }">${admin}</p>
              </div>
            </div>
          </div>
        </div>`;
    }
    else if(canView)
    {
      this.domElement.innerHTML = `
        <div class="${ styles.hideWebpart }">
        <div class="${ styles.containerhide }">
        </div>
        </div>`;
    }

Happy coding, Let me know incase of any help required…

Download the solution here

Leave a Reply

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