Responsive DataTable With Spfx Including Export Buttons

Open a command prompt. Create a directory for SPFx solution.
 
md spfx-React-DataTable
 
Navigate to the above created directory.
 
cd spfx-React-DataTable
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter to have default name (spfx-pnp-DropDown in this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the component
 
Here, we can select the target environment where we are planning to deploy the client web part, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice: SharePoint Online only (latest)
 
Place of files
 
We may choose to use the same folder or create a subfolder for our solution.
Selected choice: Same folder
 
Deployment option
 
Selecting Y will allow the app to deployed instantly to all sites and will be accessible everywhere.
Selected choice: N (install on each site explicitly)
 
Permissions to access web APIs
 
Choose if the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant.
Selected choice: N (solution contains unique permissions)
 
Type of client-side component to create
 
We can choose to create a client-side web part or an extension. Choose web part option.
Selected choice: WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
Selected choice: ReactPnpResponsiveDataTable
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 
Framework to use
 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice: React
 
Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running below command.
 
npm shrinkwrap
 
In the command prompt, type below command to open the solution in the code editor of your choice.
 
code .
 
NPM Packages Used,
 
On the command prompt, run below command.
 
npm i @pnp/logging @pnp/common @pnp/odata @pnp/sp --save
for Pollyfills
npm install --save @pnp/polyfill-ie11
 
Other Installations
 
npm i pdfmake
npm i jszip
npm install file-saver --save
npm install --save datatables.net
npm install --save datatables.net-buttons
npm install --save datatables.net-responsive
npm i jquery 
 
in ReactPnpResponsiveDataTableWebPart.ts
  1. import "@pnp/polyfill-ie11";  
  2. import { sp, Web } from '@pnp/sp';  
  3. export interface IReactPnpResponsiveDataTableWebPartProps {  
  4.   description: string;  
  5. }  
  6. export default class ReactPnpResponsiveDataTableWebPart extends BaseClientSideWebPart<IReactPnpResponsiveDataTableWebPartProps> {  
  7.   protected onInit(): Promise<void> {  
  8.     return new Promise<void>((resolve: () => void, reject: (error?: any) => void): void => {  
  9.       sp.setup({  
  10.         sp: {  
  11.           headers: {  
  12.             "Accept""application/json; odata=nometadata"  
  13.           }  
  14.         }  
  15.       });  
  16.       resolve();  
  17.     });  
  18.   }  
  19.   public render(): void {  
  20.     const element: React.ReactElement<IReactPnpResponsiveDataTableProps > = React.createElement(  
  21.       ReactPnpResponsiveDataTable,  
  22.       {  
  23.         description: this.properties.description,  
  24.         context: this.context    
  25.       }  
  26.     );  
  27.   
  28.     ReactDom.render(element, this.domElement);  
  29.   }  
  30.   
  31.   protected onDispose(): void {  
  32.     ReactDom.unmountComponentAtNode(this.domElement);  
  33.   }  
  34.   
  35.   protected get dataVersion(): Version {  
  36.     return Version.parse('1.0');  
  37.   }  
  38.   
  39.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  40.     return {  
  41.       pages: [  
  42.         {  
  43.           header: {  
  44.             description: strings.PropertyPaneDescription  
  45.           },  
  46.           groups: [  
  47.             {  
  48.               groupName: strings.BasicGroupName,  
  49.               groupFields: [  
  50.                 PropertyPaneTextField('description', {  
  51.                   label: strings.DescriptionFieldLabel  
  52.                 })  
  53.               ]  
  54.             }  
  55.           ]  
  56.         }  
  57.       ]  
  58.     };  
  59.   }  
  60. }  
In ReactPnpResponsiveDataTable.ts,
  1. import * as React from 'react';  
  2. /*import styles from './ReactPnpResponsiveDataTable.module.scss';*/  
  3. import { IReactPnpResponsiveDataTableProps } from './IReactPnpResponsiveDataTableProps';  
  4. import { escape } from '@microsoft/sp-lodash-subset';  
  5. import { IReactPnpResponsiveDataTableState } from './ReactPnpResponsiveDataTableState';  
  6. import { SPComponentLoader } from '@microsoft/sp-loader';  
  7. import * as $ from 'jquery';  
  8. import { sp, Web } from '@pnp/sp';  
  9. import 'jszip/dist/jszip';  
  10. import 'pdfmake/build/pdfmake';  
  11. import 'datatables.net';  
  12. import 'datatables.net-responsive';  
  13. import 'datatables.net-buttons';  
  14. import * as FileSaver from 'file-saver';  
  15. import 'datatables.net-buttons/js/buttons.html5';  
  16. import 'datatables.net-buttons/js/buttons.print';  
  17. SPComponentLoader.loadCss('https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap.min.css');    
  18. SPComponentLoader.loadCss('https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css');  
  19. SPComponentLoader.loadCss('https://cdn.datatables.net/buttons/1.6.0/css/buttons.dataTables.min.css');  
  20. SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js')  
  21. var sSearchtext='Search :';  
  22. var sInfotext = 'Showing _START_ to _END_ of _TOTAL_ entries';  
  23. var   sZeroRecordsText='No data available in table';  
  24. var sinfoFilteredText="(filtered from _MAX_ total records)";  
  25. var   placeholderkeyword="Keyword";  
  26. var lengthMenutxt="Show _MENU_ entries";  
  27. var firstpage="First";  
  28. var Lastpage="Last";  
  29. var Nextpage="Next";  
  30. var Previouspage="Previous";  
  31. export default class ReactPnpResponsiveDataTable extends React.Component<IReactPnpResponsiveDataTableProps, IReactPnpResponsiveDataTableState> {  
  32.   constructor(props: IReactPnpResponsiveDataTableProps, state: IReactPnpResponsiveDataTableState) {  
  33.     super(props);  
  34.     this.state = {  
  35.       Projectstatus: [{ mymilestone: "", myscore: "", id: "", Forcastedate: "", Actualdate: "", TgtResDate: "" }]  
  36.   
  37.     };  
  38.     this.fetchdatas = this.fetchdatas.bind(this);   
  39.   }  
  40.    componentDidMount(){  
  41.     this.fetchdatas();  
  42.   }  
  43.   private fetchdatas() {  
  44.     const web = new Web(this.props.context.pageContext.web.absoluteUrl);  
  45.     const list2 = sp.web.lists.getByTitle("ProjectStatus");  
  46.     let FetchProjectDetails = [];  
  47.     list2.items.select('Id,MileStone,PercentageComplete,ForcastDate,ActualDate,TargetResolutionDate').top(5000).get().then(r => {  
  48.       for (let i = 0; i < r.length; i++) {  
  49.         FetchProjectDetails.push({  
  50.           mymilestone: r[i].MileStone,  
  51.           myscore: r[i].PercentageComplete,  
  52.           id: r[i].Id,  
  53.           Forcastedate: r[i].ForcastDate,  
  54.           Actualdate: r[i].ActualDate,  
  55.           TgtResDate: r[i].TargetResolutionDate  
  56.         });  
  57.       }  
  58.       this.setState({ Projectstatus: FetchProjectDetails });  
  59.     });  
  60.   }  
  61.   public render(): React.ReactElement<IReactPnpResponsiveDataTableProps> {  
  62.     return (  
  63.       <div>  
  64.         <table className='table-responsive table table-striped table-bordered dt-responsive nowrap display' id='SpfxDatatable'>  
  65.           <thead>  
  66.             <tr>  
  67.               <th>MyMilestone</th>  
  68.               <th>MyScore</th>  
  69.               <th>Id</th>  
  70.               <th>Forcast</th>  
  71.               <th>Actual</th>  
  72.               <th>TgtRes</th>  
  73.             </tr>  
  74.           </thead>  
  75.           <tbody id='SpfxDatatableBody'>  
  76.             {this.state.Projectstatus && this.state.Projectstatus.map((item, i) => {  
  77.               return [  
  78.                   <tr key={i}>  
  79.                     <td>{item.mymilestone}</td>  
  80.                     <td>{item.myscore}</td>  
  81.                     <td>{item.id}</td>  
  82.                     <td>{item.Forcastedate}</td>  
  83.                     <td>{item.Actualdate}</td>  
  84.                     <td>{item.TgtResDate}</td>  
  85.                   </tr> 
  86.               ];  
  87.             })}  
  88.           </tbody>  
  89.         </table>  
  90.       </div>  
  91.     );  
  92.   }  
  93.   
  94.    componentDidUpdate() {  
  95.     $.extend( $.fn.dataTable.defaults, {  
  96.       responsive: true  
  97.     } );  
  98.     $("#SpfxDatatable").DataTable( {  
  99.       "info"true,  
  100.   
  101.             "pagingType"'full_numbers',  
  102.             dom: 'lBfrtip',  
  103.               
  104.             buttons: [  
  105.                 
  106.               {extend: 'copy'},  
  107.               {extend: 'csv'},                   
  108.            /*   { 
  109.                 extend: 'excel', 
  110.                 text: 'Export excel', 
  111.                 className: 'exportExcel', 
  112.                 filename: 'Export excel', 
  113.                 exportOptions: { 
  114.                   modifier: { 
  115.                     page: 'all' 
  116.                   } 
  117.                 } 
  118.               }, */  
  119.               {  
  120.                 text: 'Json',  
  121.                 action: function ( e, dt, node, config ) {  
  122.                   var data = dt.buttons.exportData();  
  123.                   var blob = new Blob([ JSON.stringify( data ) ] , {type: "text/plain;charset=utf-8"});  
  124.                   FileSaver.saveAs(blob, "Madhan.json");                
  125.                 }  
  126.             },    
  127.               {extend: 'pdf'},  
  128.               {extend: 'print'}  
  129.           ],             
  130.   "order": [],  
  131.   "language": {  
  132.     "infoEmpty":sInfotext,  
  133.       "info":sInfotext,  
  134.       "zeroRecords":sZeroRecordsText,  
  135.       "infoFiltered":sinfoFilteredText,  
  136.    "lengthMenu": lengthMenutxt,  
  137.   "search":sSearchtext,  
  138.   "paginate": {  
  139.     "first": firstpage,  
  140.     "last": Lastpage,  
  141.           "next": Nextpage,  
  142.           "previous": Previouspage  
  143. }      
  144.   }      
  145.   });  
  146.   }      
  147. }  
In ReactPnpResponsiveDataTableState.ts
  1. export interface IReactPnpResponsiveDataTableState {    
  2.     Projectstatus?:any[];  
  3. }   
In IReactPnpResponsiveDataTableProps.ts
  1. import { WebPartContext } from '@microsoft/sp-webpart-base';   
  2. export interface IReactPnpResponsiveDataTableProps {  
  3.   description: string;  
  4.   context: WebPartContext;  
  5. }  
Sample Output
 
 
Here I am using "ProjectStatus" as a list name with "MileStone,Id,PercentageComplete,Forcastdate,ActualDate,TargetResolutionDate" as Field Names
 
For DataTable Documentation plz visit here.
 
Happy Coding :)