Amazing Guide To SharePoint Framework Development With React - Part Two

In my previous article, we walked through how to create a SharePoint Framework web part with React to display the mockup contents step by step. We will continue with the same source for displaying the SharePoint data in the web part.

Walk through my previous article to create a project setup and initial page structure. Otherwise, navigate to the source in Github link and download or clone the source and navigate to the folder SPFxReactMockupData/manage lists and then run the below commands in a terminal.

npm install

This command installs the dependency modules to the project.

gulp serve

This command compiles and runs the web part with mockup data in the browser.

From the source, you can see the properties and state for React component are already declared. So, no need to worry about that.

We have initiated the static mockup data is available in the project. By using the MockupDataProvider, web part renders the mockup information in the browser for both local workbench and SharePoint workbench.

To view and render the current web part in SharePoint workbench. Open the https://tenant.sharepoint.com/_layouts/15/workbench.aspx.

Then add the ManageLists web part to the page. We will get the web part which shows mockup information given in the code.

Fetching SharePoint Data:

We have workbench.aspx page available for both local and SharePoint environments. Based on the environment type, we have to show the data dynamically.  Local workbench should show mockup data and SharePoint workbench shows the data from SharePoint.

The provider MockUpDataProvider class Sending the mockup information to the web part using getAllLists() method from MackupDataProvider.ts file. The same way, create another file for SharePoint environment. Create SharePointDataProvider.ts file under dataProvider folder.

First of all, import some dependency required for this file by adding the below lines.

  1. import { IList } from './../common/IObjects';  
  2. import { IDataProvider } from './IDataProvider';  
  3. import { IWebPartContext } from '@microsoft/sp-webpart-base';  
  4. import { SPHttpClient } from '@microsoft/sp-http';  
  • Import IList and IDataProvider to use the members declared in the IObject and IDataProvider files.
  • IWebPartContext from sp-web part-based object used to access the SharePoint current context. Based on that, we have to retrieve the object from SharePoint. This will take care of the authorization to access the SharePoint data.
  • SPHttpClient will be used to execute the SharePoint REST API call to get the response.

Add the class SharePointDataProvider to the SharePointDataProvider.ts with a constructor and getAllLists() method as given in below snippet

  1. export default class SharePointDataProvider implements IDataProvider{  
  2.     constructor(_context: IWebPartContext){  
  3.     }  
  4.   
  5.     public getAllLists(): Promise<IList[]>{          
  6.     }  
  7. }  

Declare the variables for storing current site context and site url by adding below lines before the constructor.

  1. private _webPartContext: IWebPartContext;      
  2. private _webAbsoluteUrl: string;  

Inside the constructor, set the value for the two private values by adding the below lines.

  1. this._webPartContext = _context;  
  2. this._webAbsoluteUrl = _context.pageContext.web.absoluteUrl;  

Calling the constructor updates the context and url information to the variables _webPartContext and _webAbsoluteUrl respectively.

Inside the get getAllLists method, declare the IList array

  1. let _items: IList[];  

Method getAllLists returns the promise object of IList array. So we should return the SharePoint values in the format of IList array. Add the below lines after the _items declaration.

  1. return this._webPartContext.spHttpClient.get(this._webAbsoluteUrl+"/_api/web/lists",SPHttpClient.configurations.v1)then((data:any)=>{  
  2.             //Add Each list to _items array from retrived json  
  3.             _items =[];              
  4.             if(data){  
  5.                 for(let i=0; i< data.value.length; i++){  
  6.                     let item = data.value[i];  
  7.                     var lst: IList ={  
  8.                         Title: item.Title,  
  9.                         Id: item.Id  
  10.                     }  
  11.                     _items.push(lst);  
  12.                 }  
  13.             }  
  14.   
  15.             return _items;  
  16.         }).catch((ex)=>{  
  17.             console.log("Error in retrieving List from site");  
  18.             throw ex;  
  19.         });  

this._webPartContext.spHttpClient calls the REST calls against SharePoint. And the get method sends the get request to server and the output is received in the then keyword. Get method has the configuration parameter SPHttpClient.Configurations.v1, which enables the following behaviour in the request.

  1. consoleLogging = true; jsonRequest = true; jsonResponse = true; defaultSameOriginCredentials = true; defaultODataVersion = ODataVersion.v4; requestDigest = true  

 

Within the then, the returned JSON is parsed and each item within JSON is added to the array _items with the members specified in the IList class.

Render SharePoint Values in WebPart

We have the setup with SharePoint data. And this is the time to call the SharePoint provider class in the web part to render the list's information in SharePoint workbench.

Navigate to src > manageLists > ManageListsWebPart.ts and open the file in editor

Replace the line import { Version } from '@microsoft/sp-core-library'; with the below line in the import section to import the objects to identify the environment type.

  1. import { Version } from '@microsoft/sp-core-library';  
  2. import { Version, Environment, EnvironmentType } from '@microsoft/sp-core-library';  

Add the below import lines before this MockupDataProvider import within import section.

  1. import { IDataProvider } from './dataproviders/IDataProvider';  
  2. import   SharePointProvider  from './dataproviders/SharePointDataProvider';  

To enable the webpart to identify environment type, add the onInit method to set the dataprovider based on the environment type by adding below lines before the render method in ManageListsWebPart class.

  1. private _dataProvider: IDataProvider;  
  2.   
  3.   protected onInit(): Promise<void>{      
  4.     if(Environment.type === EnvironmentType.Local){  
  5.       this._dataProvider = new MockupDataProvider();          
  6.     }else{  
  7.       this._dataProvider = new SharePointDataProvider(this.context);  
  8.     }  
  9.     return super.onInit();  
  10.   }  

The onInit method runs during the initiation of webpart and this sets values (mockup or SharePoint) to the _dataProvider variable based on the Environment.type condition.

For the SharePoint environment, the SharePointDataProvider method is requested with the parameter of current Sharepoint context information. The getAllLists method from SharePointDataProvider uses this context information to send the REST API requests to the server.

Inside the render method the replace the code provider: new MockupDataProvider() with the below line

  1. provider: new MockupDataProvider()  
  2. provider: this._dataProvider  

The render method looks like below code snippet,

  1. public render(): void {  
  2.     const element: React.ReactElement<IManageListsProps > = React.createElement(  
  3.       ManageLists,  
  4.       {  
  5.         provider: this._dataProvider  
  6.       }  
  7.     );  
  8.     ReactDom.render(element, this.domElement);  
  9.   }  

After completing the code updates, run the below command in terminal or windows powershell.

gulp serve

The command compiles and serves the localhost bundled script file to use in the webpart.

Output

Open the SharePoint workbench in the browser and add the ManageLists web part.

https://tenant.sharepoint.com/_layouts/15/workbench.aspx. We will get the output like below.

Output

The output returns the Lists Title and Id for the requested the SharePoint site in the SharePoint workbench. If you navigate to localhost workbench, you will get the mockup data.

Conclusion

Here, we have learned on how to render the SharePoint data (Lists title and ID) in SharePoint Framework using React JS. The source for this framework web part available in GitHub link.

Stay tuned for the next article on how to add one of the reacting components (DetailsList) to display the List information in an attractive way.