Display SharePoint List Data With jQuery DataTable In SharePoint Framework(SPFx) WebPart

One of the typical SharePoint customizations is to display SharePoint List data in jQuery Datable. We used to develop this using the content editor web part or custom page referencing custom JS file. With a new development-recommended approach to create client-side web parts using SharePoint framework, let us see how we can achieve the same using SharePoint Framework web part.
 
If you are not familiar or aware of SPFx web part and jQuery data table, I would request you to go through below links first.

Sample List

 
Create a list as per our requirement. For this article, we would be using the below list.
 
Create an SPFx web part, use the below options.
 
 

jQuery Packages 

 
Add the jQuery packages. Run the below 2 commands one by one in NodeJS command prompt at the project root directory. 
  1. npm install @types/jquery@2 --save  
  2. npm install @types/jqueryui --save  
This is to load Jquery package in our SPFx solution and to use jquery syntax in TypeScript file as we do in JS file.
 

DataTable Packages 

 
As the purpose of the article is to use jQuery Datatable to render list data, we would need to install the data table npm packages in our solution. As we are in luck, we do have npm packages available for datatable.net library which can be used in any node.js based project/solution. Here, we are using jQuery UI front-end framework, we can also use other front-end frameworks like bootstrap, semantic. Read more about this in details at this link
  1. npm install datatables.net  
  2. npm install datatables.net-jqui  
  3. npm install --save @types/datatables.net  
Note
Last command is to install datatable type which can be used in TypeScript, without this there is an indirect way to use data tables methods in TypeScript (which is a story not for today)
 
Now, we have our required packages installed, let us move to actual code.
 
Open SPFx solution in your favourite code editor and go to '\js-jquery-datatable\src\webparts\jqueryDataTableWp\JqueryDataTableWpWebPart.ts' .
 

Import Packages 

 
Add the below lines on top of your webpart.ts file to import packages which we installed.
  1. import { SPComponentLoader } from '@microsoft/sp-loader';  
  2. import * as $ from 'jquery';  
  3. import 'DataTables.net';  
  4. import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions} from '@microsoft/sp-http';   
Note
The first and the last import statement do not need any packages to be installed because the packages are already available as a part of SharePoint package while we created SPFx solution using the yo @microsoft/SharePoint command. SPComponentLoader will be used for loading external JS/CSS file. SPHttpClient package has methods which we can use to interact with SharePoint using REST API.
 

Render Method 

 
Replace render method with below. Please read comments in code carefully to understand the logic behind getting data and initializing DataTable with the JavaScript object (returned from REST API call).
 
Rest API used to get the list data.
  1. /_api/web/Lists/GetByTitle('CustomList')/items?$select=ID,Title,Email,Phone,Status,yes_x0020_no   
  1. public render(): void {  
  2.     // Just adding a plain table which will be converted to jquery datatable.  
  3.     this.domElement.innerHTML = `  
  4.     <table id="example" class="display" width="100%"></table>`;  
  5.     //Loading Jquery Datatable CSS file to get required look and feel, somehow It thought installing  
  6.     // datatable package will load css also but it did not worked so I had explicitly call it here.  
  7.     SPComponentLoader.loadCss("https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css");  
  8.     // getting context of current web  
  9.     let currentWebUrl = this.context.pageContext.web.absoluteUrl;  
  10.   
  11.     // Rest API endpoint to get list data, please note here we are only getting specific columns which are required.  
  12.     let requestUrl = currentWebUrl.concat("/_api/web/Lists/GetByTitle('CustomList')/items?$select=ID,Title,Email,Phone,Status,yes_x0020_no")   
  13.     // calling the get method on above REST endpoint  
  14.     this.context.spHttpClient.get(requestUrl, SPHttpClient.configurations.v1)    
  15.     .then((response: SPHttpClientResponse) => {    
  16.         if (response.ok) {    
  17.             response.json().then((responseJSON) => {    
  18.                 if (responseJSON!=null && responseJSON.value!=null){    
  19.                  // Converting data to jsonArray  
  20.                   var jsonArray = responseJSON.value.map(function (item) {  
  21.                     return [  
  22.                         item.ID,  
  23.                         item.Title,  
  24.                         item.Email,  
  25.                         item.Phone,  
  26.                         item.Status,  
  27.                         item.yes_x0020_no ? "Yes" : "No"  
  28.                     ];  
  29.                 });  
  30.   
  31.                 // Intializing Datatable by passing jsonArray, specifying columns names here, please note that this should be   
  32.                 // in sequence of above jsonArray attributes values, it would be mapped one to one.  
  33.                 $('#example').DataTable( {  
  34.                     data: jsonArray,  
  35.                     columns: [  
  36.                         { title: "ID" },  
  37.                         { title: "Title" },  
  38.                         { title: "Email" },  
  39.                         { title: "Phone" },  
  40.                         { title: "Status" },  
  41.                         { title: "Yes/No" }  
  42.                     ]  
  43.                 } );  
  44.   
  45.                 }    
  46.             });    
  47.         }    
  48.     });   
  49.   }  

Test the webpart

 
Run the 'gulp serve' command on Node JS command prompt at project/solution root directory. It will open local workbench, you can ignore this --  data would not be loaded here as it needs SharePoint context and we have not used any mock data in our code.
 
Open your workbench on SharePoint online site collection at the below URL.
 
https://dcmovies.sharepoint.com/sites/justiceleauge/_layouts/15/workbench.aspx 
 
Output
 
 
Nice and clean, you can always extend by using all the available DataTable configuration options available. 
 

Conclusion

 
In this article, we have learned the below:
  • Getting Data from SharePoint using REST API in SPFx web part
  • Mapping SharePoint REST API response data to Javascript array.
  • Displaying REST API data with Jquery data table in SPFx web part.
Hope this post was helpful. Happy coding!!!