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
- import "@pnp/polyfill-ie11";
- import { sp, Web } from '@pnp/sp';
- export interface IReactPnpResponsiveDataTableWebPartProps {
- description: string;
- }
- export default class ReactPnpResponsiveDataTableWebPart extends BaseClientSideWebPart<IReactPnpResponsiveDataTableWebPartProps> {
- protected onInit(): Promise<void> {
- return new Promise<void>((resolve: () => void, reject: (error?: any) => void): void => {
- sp.setup({
- sp: {
- headers: {
- "Accept": "application/json; odata=nometadata"
- }
- }
- });
- resolve();
- });
- }
- public render(): void {
- const element: React.ReactElement<IReactPnpResponsiveDataTableProps > = React.createElement(
- ReactPnpResponsiveDataTable,
- {
- description: this.properties.description,
- context: this.context
- }
- );
-
- ReactDom.render(element, this.domElement);
- }
-
- protected onDispose(): void {
- ReactDom.unmountComponentAtNode(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
- })
- ]
- }
- ]
- }
- ]
- };
- }
- }
In ReactPnpResponsiveDataTable.ts,
- import * as React from 'react';
-
- import { IReactPnpResponsiveDataTableProps } from './IReactPnpResponsiveDataTableProps';
- import { escape } from '@microsoft/sp-lodash-subset';
- import { IReactPnpResponsiveDataTableState } from './ReactPnpResponsiveDataTableState';
- import { SPComponentLoader } from '@microsoft/sp-loader';
- import * as $ from 'jquery';
- import { sp, Web } from '@pnp/sp';
- import 'jszip/dist/jszip';
- import 'pdfmake/build/pdfmake';
- import 'datatables.net';
- import 'datatables.net-responsive';
- import 'datatables.net-buttons';
- import * as FileSaver from 'file-saver';
- import 'datatables.net-buttons/js/buttons.html5';
- import 'datatables.net-buttons/js/buttons.print';
- SPComponentLoader.loadCss('https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap.min.css');
- SPComponentLoader.loadCss('https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css');
- SPComponentLoader.loadCss('https://cdn.datatables.net/buttons/1.6.0/css/buttons.dataTables.min.css');
- SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js')
- var sSearchtext='Search :';
- var sInfotext = 'Showing _START_ to _END_ of _TOTAL_ entries';
- var sZeroRecordsText='No data available in table';
- var sinfoFilteredText="(filtered from _MAX_ total records)";
- var placeholderkeyword="Keyword";
- var lengthMenutxt="Show _MENU_ entries";
- var firstpage="First";
- var Lastpage="Last";
- var Nextpage="Next";
- var Previouspage="Previous";
- export default class ReactPnpResponsiveDataTable extends React.Component<IReactPnpResponsiveDataTableProps, IReactPnpResponsiveDataTableState> {
- constructor(props: IReactPnpResponsiveDataTableProps, state: IReactPnpResponsiveDataTableState) {
- super(props);
- this.state = {
- Projectstatus: [{ mymilestone: "", myscore: "", id: "", Forcastedate: "", Actualdate: "", TgtResDate: "" }]
-
- };
- this.fetchdatas = this.fetchdatas.bind(this);
- }
- componentDidMount(){
- this.fetchdatas();
- }
- private fetchdatas() {
- const web = new Web(this.props.context.pageContext.web.absoluteUrl);
- const list2 = sp.web.lists.getByTitle("ProjectStatus");
- let FetchProjectDetails = [];
- list2.items.select('Id,MileStone,PercentageComplete,ForcastDate,ActualDate,TargetResolutionDate').top(5000).get().then(r => {
- for (let i = 0; i < r.length; i++) {
- FetchProjectDetails.push({
- mymilestone: r[i].MileStone,
- myscore: r[i].PercentageComplete,
- id: r[i].Id,
- Forcastedate: r[i].ForcastDate,
- Actualdate: r[i].ActualDate,
- TgtResDate: r[i].TargetResolutionDate
- });
- }
- this.setState({ Projectstatus: FetchProjectDetails });
- });
- }
- public render(): React.ReactElement<IReactPnpResponsiveDataTableProps> {
- return (
- <div>
- <table className='table-responsive table table-striped table-bordered dt-responsive nowrap display' id='SpfxDatatable'>
- <thead>
- <tr>
- <th>MyMilestone</th>
- <th>MyScore</th>
- <th>Id</th>
- <th>Forcast</th>
- <th>Actual</th>
- <th>TgtRes</th>
- </tr>
- </thead>
- <tbody id='SpfxDatatableBody'>
- {this.state.Projectstatus && this.state.Projectstatus.map((item, i) => {
- return [
- <tr key={i}>
- <td>{item.mymilestone}</td>
- <td>{item.myscore}</td>
- <td>{item.id}</td>
- <td>{item.Forcastedate}</td>
- <td>{item.Actualdate}</td>
- <td>{item.TgtResDate}</td>
- </tr>
- ];
- })}
- </tbody>
- </table>
- </div>
- );
- }
-
- componentDidUpdate() {
- $.extend( $.fn.dataTable.defaults, {
- responsive: true
- } );
- $("#SpfxDatatable").DataTable( {
- "info": true,
-
- "pagingType": 'full_numbers',
- dom: 'lBfrtip',
-
- buttons: [
-
- {extend: 'copy'},
- {extend: 'csv'},
-
-
-
-
-
-
-
-
-
-
-
- {
- text: 'Json',
- action: function ( e, dt, node, config ) {
- var data = dt.buttons.exportData();
- var blob = new Blob([ JSON.stringify( data ) ] , {type: "text/plain;charset=utf-8"});
- FileSaver.saveAs(blob, "Madhan.json");
- }
- },
- {extend: 'pdf'},
- {extend: 'print'}
- ],
- "order": [],
- "language": {
- "infoEmpty":sInfotext,
- "info":sInfotext,
- "zeroRecords":sZeroRecordsText,
- "infoFiltered":sinfoFilteredText,
- "lengthMenu": lengthMenutxt,
- "search":sSearchtext,
- "paginate": {
- "first": firstpage,
- "last": Lastpage,
- "next": Nextpage,
- "previous": Previouspage
- }
- }
- });
- }
- }
In ReactPnpResponsiveDataTableState.ts
- export interface IReactPnpResponsiveDataTableState {
- Projectstatus?:any[];
- }
In IReactPnpResponsiveDataTableProps.ts
- import { WebPartContext } from '@microsoft/sp-webpart-base';
- export interface IReactPnpResponsiveDataTableProps {
- description: string;
- context: WebPartContext;
- }
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 :)