Apply custom css to SharePoint Modern Pages using SPFx webpart

With the absence of content editor web part (CWEP) or script editor web part in SharePoint Modern experience, power users have the challenge to style the page as per their requirements.

The only approach is to create a custom SPFx component that can add the custom css onto the page. That’s it !! Easy right. But how to do it? In this blog we will look at the steps  for the same and is also a link (with steps) in case to easily build it.

This adds the overhead of managing a custom component but the simplicity of the component puts all the support on the external CSS and not the webpart itself, so easy to maintain. In other words, it means that the webpart just adds the custom CSS to the page, so the CSS does all the work.

Note: The custom CSS doesn’t solve all scenarios as would the earlier Script editor or CWEP but still could do the styling part and solve a lot of alignment issues. Also another note, applying custom inline JavaScript to the page has its challenges and don’t work. We will discuss the reason of not using custom scripts in another blog, but the advise for now is not to use custom scripts.

Deployment using Code from Repo

Git Repo link

For those who would like to get the code directly or start with, here is the link to the repo. The steps to use it are simple as below.

1. Clone the repo or download the solution

2. Open the folder in Visual Studio Code

3. Then, as with any cloned code, do the following,

gulp clean

npm install

gulp build

4. If the above doesn’t result any build errors, then go to step 7, else go to step 5

5. Fix any errors in the code

6. Test the code using gulp serve. Open the workbench and test the custom CSS using property pane. For details see below step x.

gulp serve

7. Deploy the assets using Gulp ship.

gulp --ship

8. Package the solution

gulp package-solution --ship

9. Go to Code folder and migrate to SharePoint/sources and find the sppkg file.

10. Deploy the sppkg file to App catalog of your site or tenant app catalog. For more details to how to enable site collection app catalog check here.

11. Add the app to the site

12. Add the web part to the page.

13. Edit the web part and provide the CSS class path from the property pane.

CSSExtenderWebPartProps

14. Apply the changes. The css should reflect on the site.

Building your own CSS implementor

If you are not interested to copy the code from the repo and write it yourself below are the steps. The code is not complex so way to create it.

1. Create a SPFx webpart using yeoman. Recommended to use version SPFx 1.4 or greater.

2. Add a property to read the CSS Path from.

3. Next open the .tsx file from the components folder. And add the SPComponentLoader from @microsoft/sp-loader class

4. Next use SPComponentLoader.Loadcss() method to apply the custom css onto the page. Sample code below

public render(): React.ReactElement {

if(this.props.pathtocssfile!=="")

{

SPComponentLoader.loadCss(this.props.pathtocssfile);

}

}

5. Gulp serve and test the webpart

And that’s it !!

Follow the steps from above repo section for the steps to deploy the web part to the application catalog.

Conclusion

In this blog we saw how to implement custom css on a page using some quick SPFx scripting.

Happy Coding !!

Dev Tips : Planning IE11 compatibility with SPFx components and PnPJS library

One of the common challenges I encounter when working with SPFx components is that the app doesn’t work with IE11 as expected even though it works fine with other browsers. This has delayed many of my projects and puts a lot of risk on production releases. Hence in this blog, I will try to call out some of the challenges that we might run into when deploying complex SPFx components in IE11 and other older browsers, and some workarounds/rectifications for the same.

Limitations and Challenges

To start with, lets’ start with some of the limitations for the complex components in older browsers.

  1. SPFx webparts are heavily dependant on client browsers and run in an isolated environment, so need to plan effectively for heavier data loads. For example, if you are retrieving 1000s of records from a SharePoint list, it would be recommended to page them in smaller datasets while rendering them, so the browser memory can handle it.
  2. SPFx webparts with React mostly use Promises and Async/Await functionality when used with third-party libraries such as PnPJS. The async/await are a great feature and compatible with ES6 and above. The older browsers such as IE11 cannot work through this delegation.
  3. The older browsers cannot handle promise chaining effectively which sometimes drops the delegate calls in progress. Hence the easier approach for planning the Promises call is to use them in sequence and not chaining for more than three levels.  A brief example is below.
  4. Memory management in IE 11 and some older browsers are not effective for large and complex operations (click here). Hence the effective way would be to use light weight classes and paging to pull data when required. For large datasets use paging to get the data in batches.

How to make it work with IE11?

In order for the solution work on IE11, below are few workarounds and recommendations for the same.

1. Use of IE 11 polyfill for PnPJS library. The polyfill allows to load the missing libraries before calling the dependant calls. However there could be risks as the polyfill library loads the scripts which are not included as part of PnPJS library. More details could be found here.

2. Use SPHttpClient and HttpClient. The SPHttpClient and HttpClient are core libraries of SPFx and will work fine on IE 11. Elio Struf has a quick blog on the same which talks about the both methods. Also below are quick examples of each call and usage with payload handling for request and response.
Get Operation

Add Operation

3. Avoid using Async/Await calls to minimal usage. Use ‘then’ calls and resolve calls using the response as shown above.

4. Use Ajax calls for data change calls with success and failure handlers. This is an old way of doing this but works fine with old browsers.

5. Beware when using data intensive calls such as Search and Taxonomy models with PnPJs. Use SharePoint REST calls and handle the Response JSON. We will look at it in another blog.

Conclusion

The older browsers will always create challenges with data modelling and solution development if not planned ahead of time. The golden rule is to consider browser compatibility requirements for the solution before starting any development. This will help and save lot of pain later.

Deploy SPFx web parts to a Site Collection only – Site Collection App catalog

One of the few hidden gems of SharePoint Online hosting model is Site Collection App Catalog. Yes, you read it right, Site Collection App catalog !!!, not Tenant App catalog. Don’t confuse this with delegating app catalog rights to Site Collection Administrators. This is different and the requirement is to have the app deployed and scoped to a Site Collection only.  For more details about deployment options, please check here

So what does it mean by Site Collection App catalog ? Site Collection App catalog, as the name rightly implies, is an App catalog scoped for a site collection. In other words, it elevates a Site Collection to allow hosting Apps and create a App Catalog in the Site Collection.

Steps

The Site Collection App Catalog could be enabled using the following script.

Benefits

1. Deploy apps to the Site Collection scope only. Even if tenant app setting is On in web part, the Tenant Apps are deployed to site collection scope only

2. Apps can only be added in the installed site collection and thus decreasing risk of accidental installation at other locations

3. Allow Site Collection Administrators to manage deployments

4. There is support for SharePoint Add Ins

5. When included in the package, the assets are deployed and maintain in the site collection only

6. Distributed release cycle management could allow better functionality for upgrades

Limitations

1. Lack of tracking Site Collections where the Site Collection App catalog feature is On

2. Removal of Site Collection App catalog still leaves the App catalog library but apps cannot be installed

3. No technical restrictions to prevent the web parts from accessing other site collections

Conclusion

In the above blog we saw how to use Site Collection App Catalog for deploying web parts in the restricted scope of Site Collection.

SPFx developer guide – setup and solution structure overview

Often I get enquiries to set up a SPFx development environment. It is a fairly straightforward process and some good documentation from Microsoft is available here. However, there are still many technical bits that the developers need to work out before they could start building a real world solution.

Hence in this blog, I will try to quickly outline the set up steps, solution structure overview, and at high level dependencies for anyone who is trying to jump into development of SPFx solutions. There are also few helper links and content below for anyone who looks for a quick links to SPFx repositories.

This is fairly long blog, from my blog standards :), so give yourself 2-3 min read or skip to the particular section you are interested in.

Pre-requisites

1. First and foremost, since most of the development for SPFx is done locally so you will need a laptop, desktop or Virtual machine that you have admin rights to install software.

2. Install Node LTS version, remember to install the LTS version and not the current version as SPFx toolchain is closely linked to LTS only. Link here.

3. Install Typescript or JavaScript Code editing tools. There are many tools available for the same but would recommend Visual Studio Code as it seamless integrates with the SPFx toolchain and easy to build. Install VS Code from here

Setup Steps:

1. Install Yeoman and Gulp. Just run the below command

npm install -g yo gulp

Yeoman is a scaffolding system that allows to create the initial folders and packages for the SPFx solution.

Gulp acts as a compile, build and packaging tool for SPFx packages.

2. Next we run the yo command to generate the initial solution. Below is a screenshot of the steps for sample React Webpart without tenant deployment. Choose the most appropriate for your solution.

SPFx Webpart set up

3. Install the necessary packages using npm install for development, some of the packages are below. Check helper guide section below for links to these libraries.

a. @pnpjs modules – helpful to connect and do CRUD operations on SharePoint

b. office-ui-fabric-react – this is part of SPFx scaffolding install now (from 1.4.1) but could be also explicitly installed if need latest controls.

c. msgraphclient and aadhttpclient – to connect and work with Graph client libraries and ADAL auth scenarios and much more.. This is specifically beneficial for authentication scenarios from external web apps to SharePoint or to graph. Will talk about this in an upcoming blog.

4. Install a dev certificate before testing with command below. See this link if you run into a HTTPS/2 issue.

gulp trust-dev-cert

5. Start the development. Import the components and necessary headers for eg. as below. Also add a init method to the webpart file in case you are initialising any global components such as ‘sp’ from pnpjs.

Import Tags SPFx solution - Visual Studio Code

5. Guild build – This is not a necessary step but why gulp build? as it will help compile and resolve any .scss file compile issues and not fail later the gulp serve)

6. Gulp serve to compile and troubleshoot the component in local hosting for debugging and testing. Modify launch.json to test in a hosted SharePoint site. There is a good article here to start with.

gulp serve --nobrowser

7. After build is complete, we are ready for packaging and deployment. We will look at detailed steps for these in another blog.

gulp --ship

gulp deploy-azure storage --ship (* for Azure CDN deployments only)

gulp package-solution --ship

8. After packaging the solution, you could retrieve the packaged solution (*.sppkg) from SharePoint -> solution folder in the webpart.

9. To install the solution, just drag and drop the solution in App catalog of your tenant. For details how to add the webpart to your web or ALM cycle, check this blog.

Understanding Solution structure and key files overview for a React Web part 

Below is a quick snapshot of important folders and files in the SPFx webpart solution. You could change the structure as you want but the below files are strongly typed to the solution behaviour.

  • *webpart.ts file – entry point of the web part call. Lifecycle methods and Property pane settings for the web part for located here.
Tip: Use the webpart.ts file as a Controller for your code, keep bare minimal business logic on this file
  • Components folder – Contains component files (.tsx) files for the components in the web part. (synonymous to user control in the old web part world).
Tip: Components files can also act as controls in other components, so try to reuse code as much as possible through segregrating your code into components
  • *manifest.json – Webpart ID and settings. Also default property pane settings are here
  • config.json – CDN links or inclusion for external Non AMD libraries
  • package-solution.json – npm packages and choice to include ClientAssets in SPFx package (includeClientSideAssets = true)
  • launch.json – debug and troubleshooting settings using Chrome debugger (install chrome debugger extension for the same)
  • node_modules – modules installed from npm
  • deploy-azure-storage.json – settings for deployment to Azure CDN Location
  • styling files (.scss or .css) – files that are used for styling. Yes, you could use .css files if you are not interested in using strongly types .scss styles. Just use this to include them in your code
    require('./<Filename>.css');

Helper Guides and Developer Repositories

  1. SP starter kit – Useful source for start code samples – Link
  2. SharePoint React property pane controls and web part controls project – Link
  3. PnP JS Modules – PnPjs module for SharePoint operations – Link
  4. SPFx Webpart Samples – Sample webparts and examples. Please use it for reference only – Link
  5. Office Fabric UI React controls – Responsive controls for SPFx webparts – Link. You could also use Bootstrap in SPFx, for reference, check this blog – Link

Conclusion:

In the above blog, I have tried to summarise the SPFx high level start up steps. If any step needs to be detailed, please leave a comment and will add a follow up blog on it. Thanks.

Happy Coding !!

Deploy and Add SPFx webparts to Modern Pages using OfficeDevPnP CSOM library

In the previous blog here, we looked at how to install apps on a SharePoint site. With SharePoint and Office Dev PnP CSOM, we could also add web parts to Modern Pages, both out of the box (OOB) web parts and custom web parts. For out of box web parts, refer to Chris O’Brien article here , where he has provided steps and also the web part IDs for the OOB webparts which is really helpful.

In this blog, we will look at steps to add a custom web part and set it properties.

For the below code, we will use OfficeDevPnP CSOM library. The high level steps for implementation are below:

  1. Find the page where to add the web part. For creating a modern page programmatically, refer to this link here.
  2. Find if the web part is added to the page, if not then add it using web part ID. We will read the web part ID from a JSON class where we have kept the details of the custom web part
  3. After the web part is added, then set the web part properties using JSON schema of the properties using NewtonSoft.Json.
Note: If the web part app is just installed, then it might take time for 
the web part to be ready for use. 
Hence put a wait state till the web part is loaded for use.

The below code has the steps for adding the web part programmatically using CSOM

Conclusion

The above process could be used to add web part programmatically onto a page and set it’s properties.

Happy Coding !!