سؤال

I am trying to display data in react-data-table-component according to the input given in the search field using Rest API. For eg: If a user enters name of the person the react-data-table-component will display the result of name given by user. So far what I have been able to do is that fetching all the data when a user will click on tab. Below API I am using:

$.ajax({
      url: `${this.props.siteUrl}/_api/Web/Lists/GetByTitle('APP_NAME')/items?$select=Name&$orderby=Name`,
      type: "GET",
      dataType: "json",
      headers: {
        accept: "application/json;odata=verbose",
      },
      success: (resultData) => {
        var outputData = {
          accounting: [],
        };
        console.log(resultData.d.results);
        $.each(resultData.d.results, (index, value) => {
          outputData.accounting.push({
            Name: value.Name,
          });
        });
        this.columns1 = [
          {
            name: 'Name',
            selector: 'Name',
            sortable: true,
          },
        ];
        this.rows1 = outputData.accounting;
        this.setState({ items: outputData.accounting }, () => {
        });
      },
      error: (jqXR, textStatus, errorThrown) => {
        console.log('error');
      },
    });

Below my state variables

this.state = {
      items:[ 
        { 
          Name: "",
        }],

and the component I am using 'react-data-table-component' code

<DataTable
                columns={this.columns1}
                data={this.rows1}
                selectableRows
                pagination
                highlightOnHover
                customStyles={customStyles}
              />
هل كانت مفيدة؟

المحلول

You could bind SharePoint list to Jquery DataTable Control in React SPFX solution.

  • 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 DataTable in SPFX web part.

Please follow steps:

1.Install JQuery Packages:

npm install @types/jquery@2 --save  
npm install @types/jqueryui --save
npm install datatables.net  
npm install datatables.net-jqui  
npm install --save @types/datatables.net 

2.Bind SharePoint List data to Jquery DataTable:

import * as React from 'react';
import styles from './ReactSpfx.module.scss';
import { IReactSpfxProps } from './IReactSpfxProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { SPHttpClient,SPHttpClientResponse,ISPHttpClientOptions } from '@microsoft/sp-http';
import * as $ from 'jquery';
import { SPComponentLoader } from '@microsoft/sp-loader';
import 'DataTables.net';
import {Environment,EnvironmentType} from '@microsoft/sp-core-library';

export interface ISPLists {
  value: ISPList[];
}

export interface ISPList {
  Title: string;
  Id: string;
}

export default class ReactSpfx extends React.Component<IReactSpfxProps,IMsprocesseditState> {
  public render(): React.ReactElement<IReactSpfxProps> {
  SPComponentLoader.loadCss("https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css");
    return (
              <table ref='table' className={styles.table}>
              </table>
    );
  }

  private _getListData(): Promise<ISPLists> {
    return this.props.context.spHttpClient.get(this.props.context.pageContext.web.absoluteUrl + `/_api/web/lists/getbyTitle('MyList')/items`, SPHttpClient.configurations.v1)
      .then((response: SPHttpClientResponse) => {
        return response.json();
      });
  }

  private _renderList(items: ISPList[]): void {
    let html: string = '';
    var jsonarr= items.map((item: ISPList) => {
        return [
          item.Id,
          item.Title
      ];
    });
    $(this.refs.table).DataTable( {
      data: jsonarr,
      columns: [
          { title: "ID" },
          { title: "Title" }
      ]
     });
  }

  private _renderListAsync(): void {
    if (Environment.type == EnvironmentType.SharePoint || Environment.type == EnvironmentType.ClassicSharePoint) {
          this._getListData()
            .then((response) => {
              this._renderList(response.value);
            });
        }
  }
  public componentDidMount() {
      this._renderListAsync();
 }
}

3.Test the Webpart and you can view the search box will working:

working

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى sharepoint.stackexchange
scroll top