SharePoint Framework: Retrieve and Display SharePoint List Items using REST API and React JS
Introduction
React makes it easy to create interactive UIs. It helps us to create simple views for each state in our application, efficiently update and render the right components when our data changes. In this article, we will make use of React and REST API to retrieve list items from SharePoint and display them using SharePoint Framework (SPFx) web part. But before diving into the SharePoint Framework web part creation we will see how to use REST API and React JS to retrieve and display SharePoint List Items using a simple Content Editor Web part. We will later use SharePoint Framework to work with REST and React JS.
Retrieve SharePoint List data using REST API and display using Content Editor Web Part
Let’s get started with few basics of React js that we will use with the Content Editor Web Part to display the retrieved SharePoint data.Elements are the smallest building blocks of React apps.It describes what we want to see on the UI Say for instance we have an element as shown below:
const element = <h1>Display me at root node</h1>;
reactdom.render is the starting point of the React component. Let's say we have a <div> somewhere in our HTML file:
<div id="root"></div>
So as to render our React element into the above root DOM node,we will pass both to ReactDOM.render() as :
const element = <h1>Display me at root node</h1>;
ReactDOM.render(
element,
document.getElementById('root')
);
This will display the message at root div. In our case we will be displaying the data retrieved from 'ProductSales' SharePoint list in the div named 'CarSalesData'.
ReactDOM.render(<ReactSP />, document.getElementById('CarSalesData'));
ReactSP represents the component that will be rendered at the CarSalesData div. ReactSP which is the component name is defined as plain JavaScript class which extends React.Component abstract class. We will also define at least one render method within it and will be defining the UI within this render method.
Within the class, we will also have a constructor which is the right place to initialize state that will hold the data. We will update this state with SharePoint data at a later point in the react lifecycle. If we don't have to initialize state and we are not binding any methods, we don't need to implement a constructor for our React component.
Each component has several "lifecycle methods" that we can override to run code at a particular time of the process. Methods that are prefixed with 'will' are called just before some event happens, and methods prefixed with 'did' are called just after an event happens. We will be making use of the 'componentDidMount' method to fetch data from SharePoint List and we will update the state with this data. In the render method, we will then read the state data and display it in the UI.
REACT and REST API script to display SharePoint data as Grid
The code can be saved as a text file and added to the Content Editor Web Part to display the grid web part.
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.min.js"></script>
<div id="CarSalesData"></div>
<script type="text/babel">
var tableStyle = {
display: "table",
marginLeft : "40px"
}
var panelStyle = {
background: "#91A4A7"
}
var divStyle = {
background: "#eee",
padding: "20px",
margin: "20px"
};
var headerCaptionStyle = {
background: "#4B6978",
display: "table-cell",
border: "solid",
textAlign : "center",
width : "500px",
height : "30px",
paddingTop : "3px",
color : "white",
marginLeft : "80px",
display : "block"
};
var headerStyle = {
background: "#4B6978",
display: "table-cell",
border: "solid",
textAlign : "center",
width : "100px",
height : "30px",
paddingTop : "10px",
color : "white"
};
var tableCaptionStyle = {
background: "#c6e2ff",
display: "block",
fontSize : "20px",
fontWeight: "bold",
border: "solid",
textAlign : "center",
width : "650px",
height : "30px",
paddingTop : "3px",
borderRadius: "25px",
marginLeft : "30px",
marginTop : "20px"
}
var rowCaptionStyle = {
width : "600px",
display : "table-caption",
background: "#4B6978",
textAlign : "center",
padding: "20px",
fontSize : "20px",
fontWeight :"bold",
color : "white"
};
var rowStyle = {
display : "table-row",
background: "#eee",
padding: "20px",
margin: "20px",
fontWeight :"bold"
};
var CellStyle = {
display: "table-cell",
border: "solid",
borderColor : "white",
textAlign : "center",
width : "100px",
height : "30px",
paddingTop : "10px"
}
class ReactSP extends React.Component{
debugger;
constructor(){
super();
this.state = {
items: [
{
"CarName": "",
"Quarter1": "",
"Quarter2":"",
"Quarter3": "",
"Quarter4":""
}
]
};
}
componentDidMount() {
debugger;
this.RetrieveSPData();
}
RetrieveSPData(){
var reactHandler = this;
var spRequest = new XMLHttpRequest();
spRequest.open('GET', "/sites/playground/_api/web/lists/getbytitle('ProductSales')/items",true);
spRequest.setRequestHeader("Accept","application/json");
spRequest.onreadystatechange = function(){
if (spRequest.readyState === 4 && spRequest.status === 200){
var result = JSON.parse(spRequest.responseText);
reactHandler.setState({
items: result.value
});
}
else if (spRequest.readyState === 4 && spRequest.status !== 200){
console.log('Error Occurred !');
}
};
spRequest.send();
}
render(){
debugger;
return (
<div style={panelStyle}>
<br></br>
<br></br>
<div style={tableCaptionStyle} > Demo : Retrieve SharePoint List Items using React JS </div>
<br></br>
<div style={tableStyle} >
<div style={rowCaptionStyle} > Quarterly Car Sales Data </div>
<div style={rowStyle} >
<div style={headerStyle}>Car Name</div>
<div style={headerStyle}>Quarter 1 </div>
<div style={headerStyle}>Quarter 2</div>
<div style={headerStyle}>Quarter 3</div>
<div style={headerStyle}>Quarter 4</div>
</div>
{this.state.items.map(function(item,key){
return (<div style={rowStyle} key={key}>
<div style={CellStyle}>{item.CarName}</div>
<div style={CellStyle}>{item.Quarter1}</div>
<div style={CellStyle}>{item.Quarter2}</div>
<div style={CellStyle}>{item.Quarter3}</div>
<div style={CellStyle}>{item.Quarter4}</div>
</div>);
})}
</div>
</div>
);
}
}
ReactDOM.render(<ReactSP />, document.getElementById('CarSalesData'));
</script>
Create SPFx Web Part to retrieve SharePoint List Items using REACT & REST API
In this section, we will see how to create a client web part using SharePoint Framework and React JS that displays SharePoint List data retrieved using REST API. The major project files used in this solution has been zipped and uploaded to 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 the yeoman generator using the command ‘*yo @microsoft/sharepoint’*
Edit the web part
Run Code . to create the scaffolding and open the project in Visual Studio Code. We will be required jQuery to make AJAX REST API calls. So 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';
Exploring the File Structure
We will be making use of the above-marked files to implement the solution using React.
- IReactgetItemsProps.TS: This will hold the properties that will be accessed by other files in the solution. By default, there is a description property defined, we will add another property ‘siteURL’ as well using the interface.
- ReactGetItems/modue .scss: This will contain the CSS styles that are used within the TSX file.
- ReactGetItems .tsx: This file serves as the major location where the UI and Logics are defined.
- ReactGetItemsWebPart.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 that 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 that contains the major logic processing and UI.
export default class ReactGetItemsWebPart extends BaseClientSideWebPart<IReactGetItemsWebPartProps> {
public render(): void {
const element: React.ReactElement<IReactGetItemsProps > = React.createElement(
ReactGetItems,
{
description: this.properties.description,
siteurl: this.context.pageContext.web.absoluteUrl
}
);
ReactDom.render(element, this.domElement);
}
IReactgetItemsProps.TS
This file contains the properties that will be accessed from the files and are declared using an Interface as shown below:
export interface IReactGetItemsProps {
description: string;
siteurl: string;
}
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:
.tableStyle{
display: table ;
margin-left : 100px ;
}
.panelStyle{
background: lightblue ;
}
.divStyle{
background: #eee ;
padding: 20px ;
margin: 20px ;
}
.headerCaptionStyle{
background: #4B6978 ;
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 ;
}
ReactGetItems.tsx
This is the primary file where the logic and UI is 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 that will be populated using REST API calls.
public constructor(props: IReactGetItemsProps, state: IReactGetItemsState){
super(props);
this.state = {
items: [
{
"EmployeeName": "",
"EmployeeId": "",
"Experience":"",
"Location":""
}
]
};
}
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 the REST API call within this method to retrieve the list items and add it to the state object.
public componentDidMount(){
var reactHandler = this;
jquery.ajax({
url: `${this.props.siteurl}/_api/web/lists/getbytitle('EmployeeList')/items`,
type: "GET",
headers:{'Accept': 'application/json; odata=verbose;'},
success: function(resultData) {
reactHandler.setState({
items: resultData.d.results
});
},
error : function(jqXHR, textStatus, errorThrown) {
}
});
}
Finally, the render method will read the state object and build the UI
public render(): React.ReactElement<IReactGetItemsProps> {
return (
<div className={styles.panelStyle} >
<br></br>
<br></br>
<div className={styles.tableCaptionStyle} > Demo : Retrieve SharePoint List Items using SPFx , REST API & React JS </div>
<br></br>
<div className={styles.headerCaptionStyle} > Employee Details</div>
<div className={styles.tableStyle} >
<div className={styles.headerStyle} >
<div className={styles.CellStyle}>Employee Name</div>
<div className={styles.CellStyle}>Employee Id </div>
<div className={styles.CellStyle}>Experience</div>
<div className={styles.CellStyle}>Location</div>
</div>
{this.state.items.map(function(item,key){
return (<div className={styles.rowStyle} key={key}>
<div className={styles.CellStyle}>{item.EmployeeName}</div>
<div className={styles.CellStyle}>{item.EmployeeId}</div>
<div className={styles.CellStyle}>{item.Experience}</div>
<div className={styles.CellStyle}>{item.Location}</div>
</div>);
})}
</div>
</div>
);
}
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 the SharePoint Online Workbench URL by appending ‘_layouts/15/workbench.aspx’ to the URL.
The retrieved data has been displayed as Grid as shown below:
TSX File contents for retrieving list items using REST API and REACT
The tsx file contents used to retrieve the list items via REST API is given below:
import * as React from 'react';
import styles from './ReactGetItems.module.scss';
import { IReactGetItemsProps } from './IReactGetItemsProps';
import { escape } from '@microsoft/sp-lodash-subset';
import * as jquery from 'jquery';
export interface IReactGetItemsState{
items:[
{
"EmployeeName": "",
"EmployeeId": "",
"Experience":"",
"Location":""
}]
}
export default class ReactGetItems extends React.Component<IReactGetItemsProps, IReactGetItemsState> {
public constructor(props: IReactGetItemsProps, state: IReactGetItemsState){
super(props);
this.state = {
items: [
{
"EmployeeName": "",
"EmployeeId": "",
"Experience":"",
"Location":""
}
]
};
}
public componentDidMount(){
var reactHandler = this;
jquery.ajax({
url: `${this.props.siteurl}/_api/web/lists/getbytitle('EmployeeList')/items`,
type: "GET",
headers:{'Accept': 'application/json; odata=verbose;'},
success: function(resultData) {
reactHandler.setState({
items: resultData.d.results
});
},
error : function(jqXHR, textStatus, errorThrown) {
}
});
}
public render(): React.ReactElement<IReactGetItemsProps> {
return (
<div className={styles.panelStyle} >
<br></br>
<br></br>
<div className={styles.tableCaptionStyle} > Demo : Retrieve SharePoint List Items using SPFx , REST API & React JS </div>
<br></br>
<div className={styles.headerCaptionStyle} > Employee Details</div>
<div className={styles.tableStyle} >
<div className={styles.headerStyle} >
<div className={styles.CellStyle}>Employee Name</div>
<div className={styles.CellStyle}>Employee Id </div>
<div className={styles.CellStyle}>Experience</div>
<div className={styles.CellStyle}>Location</div>
</div>
{this.state.items.map(function(item,key){
return (<div className={styles.rowStyle} key={key}>
<div className={styles.CellStyle}>{item.EmployeeName}</div>
<div className={styles.CellStyle}>{item.EmployeeId}</div>
<div className={styles.CellStyle}>{item.Experience}</div>
<div className={styles.CellStyle}>{item.Location}</div>
</div>);
})}
</div>
</div>
);
}
}
Summary
Thus we saw how to create a SharePoint Framework client web part that fetches and displays SharePoint List data using REST API and React JS. The major project files used in this solution has been zipped and uploaded at Microsoft TechNet Gallery. Feel free to download it.