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.
- import { IList } from './../common/IObjects';
- import { IDataProvider } from './IDataProvider';
- import { IWebPartContext } from '@microsoft/sp-webpart-base';
- 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
- export default class SharePointDataProvider implements IDataProvider{
- constructor(_context: IWebPartContext){
- }
-
- public getAllLists(): Promise<IList[]>{
- }
- }
Declare the variables for storing current site context and site url by adding below lines before the constructor.
- private _webPartContext: IWebPartContext;
- private _webAbsoluteUrl: string;
Inside the constructor, set the value for the two private values by adding the below lines.
- this._webPartContext = _context;
- 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
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.
- return this._webPartContext.spHttpClient.get(this._webAbsoluteUrl+"/_api/web/lists",SPHttpClient.configurations.v1)then((data:any)=>{
-
- _items =[];
- if(data){
- for(let i=0; i< data.value.length; i++){
- let item = data.value[i];
- var lst: IList ={
- Title: item.Title,
- Id: item.Id
- }
- _items.push(lst);
- }
- }
-
- return _items;
- }).catch((ex)=>{
- console.log("Error in retrieving List from site");
- throw ex;
- });
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.
- 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 WebPartWe 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.
- import { Version } from '@microsoft/sp-core-library';
- import { Version, Environment, EnvironmentType } from '@microsoft/sp-core-library';
Add the below import lines before this MockupDataProvider import within import section.
- import { IDataProvider } from './dataproviders/IDataProvider';
- 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.
- private _dataProvider: IDataProvider;
-
- protected onInit(): Promise<void>{
- if(Environment.type === EnvironmentType.Local){
- this._dataProvider = new MockupDataProvider();
- }else{
- this._dataProvider = new SharePointDataProvider(this.context);
- }
- return super.onInit();
- }
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
- provider: new MockupDataProvider()
- provider: this._dataProvider
The render method looks like below code snippet,
- public render(): void {
- const element: React.ReactElement<IManageListsProps > = React.createElement(
- ManageLists,
- {
- provider: this._dataProvider
- }
- );
- ReactDom.render(element, this.domElement);
- }
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.
OutputOpen 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.
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.
ConclusionHere, 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.