Click here to Skip to main content
13,198,325 members (77,016 online)
Click here to Skip to main content
Add your own
alternative version

Stats

2.8K views
2 bookmarked
Posted 21 Sep 2017

SharePoint Framework aka SPFx Web part using React & REST API

Rate this:
Please Sign up or sign in to vote.
SharePoint Framework WebPart to retrieve list items using React & REST API

Introduction

The SharePoint Framework (SPFx) provides full support for client-side SharePoint development. This provides easy integration with SharePoint data. It is compatible with modern technologies and tool. You can use your own IDE no need to purchase Visual Studio. Moreover SPFx is responsive in design.

This article talks about using the SharePoint Framework web part with React as Framework. The whole article will walk you through the complete lifecycle from Pre Requisite , Understanding SPFx Web Part, Configure, Build & Deploy.

Using the code

The code uses React to do the rendering part on the SharePoint Page. REST API fetches the data from SharePoint list.

The data source gets refreshed at a particular interval of time. Page only gets updated if there is a change in the data values as compared to current DOM. No need to refresh the page to see updated data. As soon as the state changes, React does the job of updating DOM.

Pre Requisite

Below are the pre requisites from installation and learning point of view. References are provided for installation links below. You will also need to create a SharePoint Developer & AppCatalog site, these will come handy while deploying the code.

Don't forget to create the SharePoint list with columns as shown below.

Installation

Create App Catalog & Developer Site

Create SharePoint List

Create SharePoint list using below columns of type text.

Create SPFX Web Part

Once the installation of all required components is completed, it's time to create SPFx webpart. Run below command  and select options as displayed in below screen. This command initiates yeoman to start creating a SharePoint web part.

yo @microsoft/sharepoint 

It takes a while to create the web part.

Install Jquery

npm install --save jquery
npm install --save @types/jquery

Understanding SPFx WebPart File Structure

Open newly created solution in VSCode using code . in command prompt. There are many files in the whole solution, below are the important files which we will talk about throughout the article.

Sanity check

Let’s check if solution builds using gulp.

Run below command in your command prompt window. Make sure you are in the directory where web part is created.

gulp build

The solution builds, let’s start understanding and updating files in the solution.

ReactGetItems.module.scss

This is like css file for SPFx web part. Overwrite your file with below code.

.tableStyle{  
    display:  table ;
    margin-left :  50px ;
}
.panelStyle{  
   background:  white ;
}

.divStyle{
background:  #eee ;
padding:  20px ;
margin:  20px ;
}

.headerCaptionStyle{
background:  white ;
display:  table-row ;
    border:  solid ;
    text-align :  center ;
    width :  420px ;
    height :  30px ;
    padding-top :  3px ;
    color :  white ;
    margin-left :  100px ;
    display :  block ;
}

.headerStyle{
background:  #4B6978 ;
display:  table-row ;
    border:  solid ;
    text-align :  center ;
    width :  100px ;
    height :  30px ;
    padding-top :  10px ;
    color :  white ;
}

.tableCaptionStyle{
background:#4B6978 ;
display:  block ;
font-size :  20px ;
font-weight:  bold ; 
    border:  solid ;
    text-align :  center ;
    width :  650px ;
    height :  30px ;
    padding-top :  3px ;
    border-radius:  25px ;
    margin-left :  30px ;
    margin-top :  20px ;
    color:white;
}

.rowCaptionStyle{
width :  600px ;
display :   table-caption ;
background:  #4B6978 ;
text-align :  center ;
padding:  20px ;
font-size :  20px ;
font-weight : bold ;
color :  white ;
}

.rowStyle{
display :   table-row ;
background:  #eee ;
padding:  20px ;
margin:  20px ;
font-weight : bold ;
}

.CellStyle{  
    display:  table-cell ; 
    border:  solid ;
     border-color :  white ;
    text-align :  center ;
    width :  100px ;
    height :  30px ;
    padding-top :  10px ;
    
}  

IReactSpfxWebPartProps.ts

Let’s update our IReactSpfxWebPartProps.ts. This is our interface for React.

Siteurl property is used for passing the site in context to webpart. Description is the description of your webpart.

export interface IReactSpfxWebPartProps {
  description: string;
  siteurl: string;
}

ReactSpFxWebPart.tsx

This is the most important file which is generated as we chose React Framewrok. Overwrite the files in your solution with below code.

  • IReactSpfxState : Interface for the state
  • ReactGetItems: Class File
  • constructor: Intitalizes State
  • componentDidMount: React Component
  • fetchDatafromSharePointList: This method uses REST API to fetch data
  • render: Rendering the html 
import * as React from 'react';
import styles from './ReactSpfxWebPart.module.scss';
import { IReactSpfxWebPartProps } from './IReactSpfxWebPartProps';
import * as jquery from 'jquery';

export interface IReactSpfxState{  
  items:[  
        {  
          "Courses": "", 
          "Credit": "", 
          "Department":"",
        }]  
}  

export default class ReactGetItems extends React.Component<IReactSpfxWebPartProps, IReactSpfxState> {

  public constructor(props: IReactSpfxWebPartProps, state: IReactSpfxState){  
    super(props); 
    
    this.state = {  
      items: [  
        {  
          "Courses": "", 
          "Credit": "", 
          "Department":"",
         
        }  
      ]  
    };  
  }  
  
private componentDidMount() {
     setInterval(
      () => this.fetchDatafromSharePointList(),
      1000
    );
  }

private fetchDatafromSharePointList()
{
  var reactHandler = this;  
    jquery.ajax({  
        url: `${this.props.siteurl}/_api/web/lists/getbytitle('CourseDetails')/items`,  
        type: "GET",  
        headers:{'Accept': 'application/json; odata=verbose;'},  
        success: function(resultData) {  
          /*resultData.d.results;*/  
          reactHandler.setState({  
            items: resultData.d.results  
          });  
        },  
        error : function(jqXHR, textStatus, errorThrown) {  
        }  
    });  
}

  public render(): React.ReactElement<IReactSpfxWebPartProps> {
    
     return (  
      <div className={styles.panelStyle} > 
        
          <div className={styles.tableCaptionStyle} >Fetch 
          Course Details from SharePointList using SPFx,RESTAPI,React JS
            Data on page changes with change in the SharePointList  </div>
         
           <div className={styles.headerCaptionStyle} >Course Details</div>
          <div className={styles.tableStyle} >   
            
            <div className={styles.headerStyle} >  
              <div className={styles.CellStyle}>Courses</div>  
              <div className={styles.CellStyle}>Credit </div>  
              <div className={styles.CellStyle}>Department</div>  
                
                     
            </div>  
            
              {this.state.items.map(function(item,key){  
                
                return (<div className={styles.rowStyle} key={key}>  
                    <div className={styles.CellStyle}>{item.Courses}</div>  
                    <div className={styles.CellStyle}>{item.Credit}</div>  
                     <div className={styles.CellStyle}>{item.Department}</div>
   	 	              
   	 	  
                  </div>);  
              })}  
                    
          </div>  
        </div>  


    );  
  }  
  
}        

ReactSpfxWebPartWebPart.ts

This is the main file created by SPFx. This interacts with React files under the Component Folder. Eventually the rendering happens here.

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
  BaseClientSideWebPart,
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-webpart-base';

import * as strings from 'reactSpfxWebPartStrings';
import ReactSpfxWebPart from './components/ReactSpfxWebPart';
import { IReactSpfxWebPartProps } from './components/IReactSpfxWebPartProps';
import { IReactSpfxWebPartWebPartProps } from './IReactSpfxWebPartWebPartProps';

export default class ReactSpfxWebPartWebPart extends BaseClientSideWebPart<IReactSpfxWebPartWebPartProps> {

  public render(): void {
    const element: React.ReactElement<IReactSpfxWebPartProps > = React.createElement(
      ReactSpfxWebPart,
      {
        description: this.properties.description,  
        siteurl: this.context.pageContext.web.absoluteUrl
      }
    );

    ReactDom.render(element, this.domElement);
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

IReactSpfxWebPartWebPartProps.ts

Interface for WebPart Properties.

export interface IReactSpfxWebPartWebPartProps {
  description: string;
}

Configurations

copy-assets.json

Folder location to be copied to SharePoint Assets library.

{
  "deployCdnPath": "temp/deploy"
}

write-manifests.json

All the files created under temp/deploy should be copied here in order for React webpart to work.

{
  "cdnBasePath": "https://yourtenant/sites/intranet/Site%20Assets"
}

package-solution.json

Most of the fields are relevant. Most important one is zippedpackage. This is the location where the package is created. 

{
  "solution": {
    "name": "react-spfx-web-part-client-side-solution",
    "id": "7d2fa690-094d-4445-b012-97d462b335ae",
    "version": "1.0.0.0",
    "skipFeatureDeployment": true
  },
  "paths": {
    "zippedPackage": "solution/react-spfx-web-part.sppkg"
  }
}

ReactSpfxWebPartWebPart.manifest.json

{
  "$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",

  "id": "3a5f40ec-b0c9-4a4f-acc1-24be14e318f2",
  "alias": "ReactSpfxWebPartWebPart",
  "componentType": "WebPart",

  // The "*" signifies that the version should be taken from the package.json
  "version": "*",
  "manifestVersion": 2,

  // If true, the component can only be installed on sites where Custom Script is allowed.
  // Components that allow authors to embed arbitrary script code should set this to true.
  // https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
  "requiresCustomScript": false,

  "preconfiguredEntries": [{
    "groupId": "3a5f40ec-b0c9-4a4f-acc1-24be14e318f2",
    "group": { "default": "Under Development" },
    "title": { "default": "ReactSpfxWebPart" },
    "description": { "default": "Retrieving list 
    items and auto refresh on change of data on SharePoint List" },
    "officeFabricIconFontName": "Page",
    "properties": {
      "description": "ReactSpfxWebPart"
    }
  }]
}

Build your Project

We will use gulp for building the project. Run below commands to start building the project. Once the project gets built successfully, you will see some files under the temp/deploy folder. These are files which contain bundled JavaScript and metadata files and are necessary for the webpart to work on SharePoint.

This creates files under temp/deploy – which needs to be copied to Assets folder of your site.

gulp build
gulp -ship

Running below commands creates sppkg  in your  target path.

gulp bundle --ship
gulp package-solution --ship

Folder Structure

Below screenshot gives an idea to find the necessary files for deployment to SharePoint.

SharePoint & Local Workbench

Type below command in command prompt. This command starts gulp and opens up a local workbench in browser.

gulp serve

This helps testing the web part before deploying the package to SharePoint. Web part can be tested on local as well as SharePoint workbench.

Testing on SharePoint Workbench will retrieve data from SharePoint List.

Local WorkBench

Testing on local workbench will only retrieve data if mock data has been created.

 

Deploy

It's time to deploy the package file to SharePoint App Catalog site.

WebPart Deployed on SharePoint

Once the webpart is added to AppCatalog, it should be available to add on SharePoint Developer or any other site collection.

References

https://dev.office.com/sharepoint/docs/spfx/sharepoint-framework-overview

https://facebook.github.io/react

http://yeoman.io

https://gulpjs.com

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ashish Rastogi @11819728
Architect
United States United States
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
SuggestionNice Pin
Filevandrel25-Sep-17 20:56
memberFilevandrel25-Sep-17 20:56 
GeneralRe: Nice Pin
Ashish Rastogi @1181972826-Sep-17 5:11
memberAshish Rastogi @1181972826-Sep-17 5:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171020.1 | Last Updated 22 Sep 2017
Article Copyright 2017 by Ashish Rastogi @11819728
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid