Create SharePoint Framework Web Part To Retrieve SharePoint List Items Using REACT And REST API

SharePoint Framework is the new development model in which lots of work has been going on in the past year. It went to General Availability on Feb 232017. It is a page and Web Part model that provides full support for client-side SharePoint development, easy integration with SharePoint data and support for open source tooling. With SharePoint Framework, you can use modern Web technologies and tools in your preferred development environment to build productive experiences and apps in SharePoint.

In this article, we will see how to create a client Web Part, using SharePoint Framework and React JS that displays SharePoint List data , which is retrieved, using REST API. The major project files used in this solution have been zipped and uploaded at Microsoft TechNet Gallery. Feel free to download it.

Let’s get started with the creation of the project by creating a directory.

md REACTGetItems
cd REACTGetItems

Run yeoman generator, using the command ‘yo @microsoft/sharepoint’.

SharePoint

SharePoint


Edit the Web Part

Run the code to create the scaffolding and open the project in Visual Studio Code. We will be requiring jQuery to make AJAX REST API calls. Thus, let’s install jQuery, using NPM, as shown below.

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

Later, we will import them to the solution in the ReactGetItems.tsx file, using

import * as jquery from 'jquery';

SharePoint

Exploring the file structure

SharePoint

We will be making use of the above marked files to implement the solution, using React.

  • TS- This will hold the properties, which will be accessed by other files in the solution. By default, there is a defined description property, which we will add to another property ‘siteURL’ as well using the interface.
  • ReactGetItems/modue.scss-  This will contain the CSS styles, which are used within the TSX file.
  • tsx- This file serves as the major location, where the UI and Logics are defined.
  • ts- This acts as the starting point of the control flow and data rendering phase is initiated from this file, using the ReactDom.render method.

ReactGetItemsWebPart.ts

The rendering of the Web Part is initiated from the ReactGetItemsWebPart TS file . Here, ReactDom.render method takes the first parameter as the element, which should be rendered (after processing some logic) at the second parameter. The element is defined by the class ‘ReactGetItems’. ReactGetItems extends React.Component in the ReactGetItems.tsx file contains the major logic processing and UI.

  1. export default class ReactGetItemsWebPart extends BaseClientSideWebPart<IReactGetItemsWebPartProps> {  
  2.   
  3.   public render(): void {  
  4.     const element: React.ReactElement<IReactGetItemsProps > = React.createElement(  
  5.       ReactGetItems,  
  6.       {  
  7.         description: this.properties.description,    
  8.         siteurl: this.context.pageContext.web.absoluteUrl  
  9.       }  
  10.     );  
  11.   
  12.     ReactDom.render(element, this.domElement);  
  13.   }  

IReactgetItemsProps.TS

This file contains the properties, which will be accessed across the files and are declared, using an Interface, as shown below.

  1. export interface IReactGetItemsProps {  
  2.   description: string;  
  3.    siteurl: string;   
  4. }  

ReactGetItems/modue.scss

The CSS style used by the Web Part is defined within this file The CSS used for our Web Part is given below.

  1. .tableStyle{    
  2.           display:  table ;  
  3.           margin-left :  100px ;  
  4.       }  
  5. .panelStyle{    
  6.          background:  lightblue ;  
  7.       }  
  8.      
  9. .divStyle{  
  10.     background:  #eee ;  
  11.     padding:  20px ;  
  12.     margin:  20px ;  
  13.    }  
  14.      
  15. .headerCaptionStyle{  
  16.           background:  #4B6978 ;  
  17.           display:  table-row ;  
  18.           border:  solid ;  
  19.           text-align :  center ;  
  20.           width :  420px ;  
  21.           height :  30px ;  
  22.           padding-top :  3px ;  
  23.           color :  white ;  
  24.           margin-left :  100px ;  
  25.           display :  block ;  
  26.    }  
  27.      
  28.    .headerStyle{  
  29.      background:  #4B6978 ;  
  30.      display:  table-row ;  
  31.           border:  solid ;  
  32.           text-align :  center ;  
  33.           width :  100px ;  
  34.           height :  30px ;  
  35.           padding-top :  10px ;  
  36.           color :  white ;  
  37.    }  
  38.      
  39.    .tableCaptionStyle{  
  40.      background:#4B6978 ;  
  41.      display:  block ;  
  42.      font-size :  20px ;  
  43.      font-weight:  bold ;   
  44.           border:  solid ;  
  45.           text-align :  center ;  
  46.           width :  650px ;  
  47.           height :  30px ;  
  48.           padding-top :  3px ;  
  49.           border-radius:  25px ;  
  50.           margin-left :  30px ;  
  51.           margin-top :  20px ;  
  52.           color:white;  
  53.    }  
  54.      
  55.      
  56.    .rowCaptionStyle{  
  57.     width :  600px ;  
  58.     display :   table-caption ;  
  59.     background:  #4B6978 ;  
  60.     text-align :  center ;  
  61.     padding:  20px ;  
  62.      font-size :  20px ;  
  63.     font-weight : bold ;  
  64.     color :  white ;  
  65.    }  
  66.      
  67.   .rowStyle{  
  68.     display :   table-row ;  
  69.     background:  #eee ;  
  70.     padding:  20px ;  
  71.     margin:  20px ;  
  72.     font-weight : bold ;  
  73.    }  
  74.      
  75.    .CellStyle{    
  76.           display:  table-cell ;   
  77.           border:  solid ;  
  78.            border-color :  white ;  
  79.           text-align :  center ;  
  80.           width :  100px ;  
  81.           height :  30px ;  
  82.           padding-top :  10px ;            
  83.       }   

ReactGetItems.tsx

This is the primary file, where the logic and UI are written. ReactDOM.render method in the ReactGetItemsWebPart file passes the control over to this file. Class ReactGetItems extends React.Component and implements a constructor, where the state objects are initialized. The state object contains the list columns, which will be populated, using REST API calls.

  1. public constructor(props: IReactGetItemsProps, state: IReactGetItemsState){    
  2.     super(props);    
  3.     this.state = {    
  4.       items: [    
  5.         {    
  6.           "EmployeeName""",    
  7.           "EmployeeId""",    
  8.           "Experience":"",    
  9.           "Location":""  
  10.         }    
  11.       ]    
  12.     };    
  13.   }    

The class also contains componentDidMount method implementation, which will be called after mounting of the component. We can also make use of componentWillMount, which is synchronous in nature. We will make REST API call within this method to retrieve the list items and add it to the state object.

  1. public componentDidMount(){    
  2.     var reactHandler = this;    
  3.     jquery.ajax({    
  4.         url: `${this.props.siteurl}/_api/web/lists/getbytitle('EmployeeList')/items`,    
  5.         type: "GET",    
  6.         headers:{'Accept''application/json; odata=verbose;'},    
  7.         success: function(resultData) {    
  8.           reactHandler.setState({    
  9.             items: resultData.d.results    
  10.           });    
  11.         },    
  12.         error : function(jqXHR, textStatus, errorThrown) {    
  13.         }    
  14.     });    
  15.   }    

Finally, Render method will read the state object and build the UI.

  1. public render(): React.ReactElement<IReactGetItemsProps> {  
  2.    return (    
  3.   
  4.       <div className={styles.panelStyle} >   
  5.         <br></br>  
  6.    
  7.         <br></br>   
  8.         <div className={styles.tableCaptionStyle} > Demo : Retrieve SharePoint List Items using SPFx , REST API  & React JS  </div>  
  9.         <br></br>  
  10.          <div className={styles.headerCaptionStyle} > Employee Details</div>  
  11.         <div className={styles.tableStyle} >     
  12.             
  13.           <div className={styles.headerStyle} >    
  14.             <div className={styles.CellStyle}>Employee Name</div>    
  15.             <div className={styles.CellStyle}>Employee Id </div>    
  16.             <div className={styles.CellStyle}>Experience</div>    
  17.               <div className={styles.CellStyle}>Location</div>                       
  18.           </div>    
  19.             
  20.             {this.state.items.map(function(item,key){    
  21.                 
  22.               return (<div className={styles.rowStyle} key={key}>    
  23.                   <div className={styles.CellStyle}>{item.EmployeeName}</div>    
  24.                   <div className={styles.CellStyle}>{item.EmployeeId}</div>    
  25.                    <div className={styles.CellStyle}>{item.Experience}</div>  
  26.                       <div className={styles.CellStyle}>{item.Location}</div>  
  27.             
  28.                 </div>);    
  29.             })}                        
  30.         </div>    
  31.       </div>    
  32.   );    
  33. }    

Test the Web Part in SharePoint Online

Now, let’s test the solution in SharePoint Online Workbench. Run Gulp Serve in the node command and head over to SharePoint Online Workbench URL by appending ‘_layouts/15/workbench.aspx’ to the URL.

SharePoint

The retrieved data has been displayed as a Grid, as shown below.

SharePoint


TSX file contents for retrieving list items using REST API and REACT

TSX file contents are used to retrieve the list items via REST API are given below.

  1. import * as React from 'react';  
  2. import styles from './ReactGetItems.module.scss';  
  3. import { IReactGetItemsProps } from './IReactGetItemsProps';  
  4. import { escape } from '@microsoft/sp-lodash-subset';  
  5. import * as jquery from 'jquery';  
  6.   
  7. export interface IReactGetItemsState{    
  8.   items:[    
  9.         {    
  10.           "EmployeeName""",    
  11.           "EmployeeId""",    
  12.           "Experience":"",    
  13.           "Location":""  
  14.         }]    
  15. }    
  16.   
  17. export default class ReactGetItems extends React.Component<IReactGetItemsProps, IReactGetItemsState> {  
  18.   
  19.   public constructor(props: IReactGetItemsProps, state: IReactGetItemsState){    
  20.     super(props);    
  21.     this.state = {    
  22.       items: [    
  23.         {    
  24.           "EmployeeName""",    
  25.           "EmployeeId""",    
  26.           "Experience":"",    
  27.           "Location":""  
  28.         }    
  29.       ]    
  30.     };    
  31.   }    
  32.     
  33.   public componentDidMount(){    
  34.     var reactHandler = this;    
  35.     jquery.ajax({    
  36.         url: `${this.props.siteurl}/_api/web/lists/getbytitle('EmployeeList')/items`,    
  37.         type: "GET",    
  38.         headers:{'Accept''application/json; odata=verbose;'},    
  39.         success: function(resultData) {             
  40.           reactHandler.setState({    
  41.             items: resultData.d.results    
  42.           });    
  43.         },    
  44.         error : function(jqXHR, textStatus, errorThrown) {    
  45.         }    
  46.     });    
  47.   }    
  48.     
  49.   
  50.   public render(): React.ReactElement<IReactGetItemsProps> {  
  51.      return (    
  52.   
  53.         <div className={styles.panelStyle} >   
  54.           <br></br>  
  55.      
  56.           <br></br>   
  57.           <div className={styles.tableCaptionStyle} > Demo : Retrieve SharePoint List Items using SPFx , REST API  & React JS  </div>  
  58.           <br></br>  
  59.            <div className={styles.headerCaptionStyle} > Employee Details</div>  
  60.           <div className={styles.tableStyle} >     
  61.               
  62.             <div className={styles.headerStyle} >    
  63.               <div className={styles.CellStyle}>Employee Name</div>    
  64.               <div className={styles.CellStyle}>Employee Id </div>    
  65.               <div className={styles.CellStyle}>Experience</div>    
  66.                 <div className={styles.CellStyle}>Location</div>    
  67.                        
  68.             </div>    
  69.               
  70.               {this.state.items.map(function(item,key){    
  71.                   
  72.                 return (<div className={styles.rowStyle} key={key}>    
  73.                     <div className={styles.CellStyle}>{item.EmployeeName}</div>    
  74.                     <div className={styles.CellStyle}>{item.EmployeeId}</div>    
  75.                      <div className={styles.CellStyle}>{item.Experience}</div>  
  76.                       <div className={styles.CellStyle}>{item.Location}</div>  
  77.             
  78.                   </div>);    
  79.               })}    
  80.                       
  81.           </div>    
  82.         </div>    
  83.     );    
  84.   }      
  85. }  

Summary

Thus, we saw how to create a SharePoint Framework Client Web Part that retrieves and displays List Items, using REST API and React JS.The major project files used in this solution have been zipped and uploaded at Microsoft TechNet Gallery. Feel free to download it.

Up Next
    Ebook Download
    View all
    Learn
    View all