Search results

Data Binding

The Grid uses DataManager which supports both RESTful JSON data services binding and local JavaScript object array binding. The dataSource property can be assigned either with the instance of DataManager or JavaScript object collection. It supports two kind of data binding method they are,

  • Local data
  • Remote data

Local Data

To bind local data to the grid, you can assign a JavaScript object array to the dataSource property. The local data source can also be provided as an instance of the DataManager.

Source
Preview
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridComponent, ColumnsDirective, ColumnDirective } from '@syncfusion/ej2-react-grids';
import { data } from '../datasource.ts';

class App extends React.Component<{}, {}>{
    public data: Object[] = data.slice(0, 7);
    render() {
        return <GridComponent dataSource={this.data} height={315}>
                <ColumnsDirective>
                    <ColumnDirective field='OrderID' headerText='Order ID' width='120' textAlign="Right"></ColumnDirective>
                    <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipName' headerText='Ship Name' width='150'></ColumnDirective>
                </ColumnsDirective>
               </GridComponent>
    }
}
ReactDOM.render(<App />, document.getElementById('grid'));

By default DataManager uses JsonAdaptor for local data-binding.

Remote Data

To bind remote data to grid component, assign service data as an instance of DataManager to the dataSource property. To interact with remote data source, provide the endpoint url.

Source
Preview
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridComponent, ColumnsDirective, ColumnDirective } from '@syncfusion/ej2-react-grids';
import { DataManager, ODataAdaptor } from '@syncfusion/ej2-data';

class App extends React.Component<{}, {}>{
    public data = new DataManager({
                      url: 'https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders/',
                    });
    render() {
        return <GridComponent dataSource={this.data}>
                <ColumnsDirective>
                    <ColumnDirective field='OrderID' headerText='Order ID' width='120' textAlign="Right"></ColumnDirective>
                    <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipName' headerText='Ship Name' width='150'></ColumnDirective>
                </ColumnsDirective>
               </GridComponent>
    }
}
ReactDOM.render(<App />, document.getElementById('grid'));

By default DataManager uses ODataAdaptor for remote data-binding.

Binding with OData Services

OData is standardized protocol for creating and consuming data. You can retrieve data from OData service using DataManager. You can refer to the following code example of remote Data binding using OData service.

Source
Preview
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridComponent, ColumnsDirective, ColumnDirective } from '@syncfusion/ej2-react-grids';
import { DataManager, ODataAdaptor } from '@syncfusion/ej2-data';

class App extends React.Component<{}, {}>{
    public data = new DataManager({
                     url: 'https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders/',
                     adaptor: new ODataAdaptor,
                     crossDomain: true
                    });
    render() {
        return <GridComponent dataSource={this.data}>
                <ColumnsDirective>
                    <ColumnDirective field='OrderID' headerText='Order ID' width='120' textAlign="Right"></ColumnDirective>
                    <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipName' headerText='Ship Name' width='150'></ColumnDirective>
                </ColumnsDirective>
               </GridComponent>
    }
}
ReactDOM.render(<App />, document.getElementById('grid'));

Binding with OData v4 services

The ODataV4 is an improved version of OData protocols, and the DataManager can also retrieve and consume OData v4 services. For more details on OData v4 services, refer to the odata documentation. To bind OData v4 service, use the ODataV4Adaptor.

Source
Preview
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridComponent, ColumnsDirective, ColumnDirective } from '@syncfusion/ej2-react-grids';
import { DataManager, ODataV4Adaptor } from '@syncfusion/ej2-data';

class App extends React.Component<{}, {}>{
    public data = new DataManager({
                      url: 'http://services.odata.org/V4/Northwind/Northwind.svc/Orders/?$top=7',
                      adaptor: new ODataV4Adaptor
                    });
    render() {
        return <GridComponent dataSource={this.data}>
                <ColumnsDirective>
                    <ColumnDirective field='OrderID' headerText='Order ID' width='120' textAlign="Right"></ColumnDirective>
                    <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipName' headerText='Ship Name' width='150'></ColumnDirective>
                </ColumnsDirective>
               </GridComponent>
    }
}
ReactDOM.render(<App />, document.getElementById('grid'));

Web API

You can use WebApiAdaptor to bind grid with Web API created using OData endpoint.

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridComponent, ColumnsDirective, ColumnDirective } from '@syncfusion/ej2-react-grids';
import { DataManager, WebApiAdaptor } from '@syncfusion/ej2-data';

class App extends React.Component<{}, {}>{
    public data = new DataManager({
                      url: '/api/OrderApi',
                      adaptor: new WebApiAdaptor
                    });
    render() {
        return <GridComponent dataSource={this.data}>
                <ColumnsDirective>
                    <ColumnDirective field='OrderID' headerText='Order ID' width='120' textAlign="Right"></ColumnDirective>
                    <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipName' headerText='Ship Name' width='150'></ColumnDirective>
                </ColumnsDirective>
               </GridComponent>
    }
}
ReactDOM.render(<App />, document.getElementById('grid'));

The response object should contain properties Items and Count whose values are collection of entities and total count of the entities respectively.

The sample response object should look like below.

{
    Items: [{..}, {..}, {..}, ...],
    Count: 830
}

Remote Save Adaptor

You may need to perform all Grid Actions in client-side except the CRUD operations, that should be interacted with server-side to persist data. It can be achieved in Grid by using RemoteSaveAdaptor.

Datasource must be set to json property and set RemoteSaveAdaptor to the adaptor property. CRUD operations can be mapped to server-side using updateUrl, insertUrl, removeUrl, batchUrl, crudUrl properties.

You can use the following code example to use RemoteSaveAdaptor in Grid.

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridComponent, Inject, ColumnsDirective, ColumnDirective, Edit, Toolbar, EditSettingsModel, ToolbarItems } from '@syncfusion/ej2-react-grids';
import { DataManager, RemoteSaveAdaptor } from '@syncfusion/ej2-data';
import { data } from '../datasource.ts';

class App extends React.Component<{}, {}>{
    public dataSource = new DataManager({
                        json: data,
                        adaptor: new RemoteSaveAdaptor,
                        insertUrl: '/Home/Insert',
                        updateUrl: '/Home/Update',
                        removeUrl: '/Home/Delete'
                    });
    public toolbarOptions: any = ['Add', 'Edit', 'Delete', 'Update', 'Cancel'];
    public editSettings: any = { allowEditing: true, allowAdding: true, allowDeleting: true };

    render() {
        return <GridComponent dataSource={this.dataSource} editSettings={this.editSettings} toolbar={this.toolbarOptions}>
                    <ColumnsDirective>
                        <ColumnDirective field='OrderID' headerText='Order ID' isPrimaryKey={true} width='120' textAlign="Right"></ColumnDirective>
                        <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'></ColumnDirective>
                        <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
                        <ColumnDirective field='ShipName' headerText='Ship Name' width='150'></ColumnDirective>
                    </ColumnsDirective>
                    <Inject services={[Edit, Toolbar]} />
               </GridComponent>
    }
}
ReactDOM.render(<App />, document.getElementById('grid'));

The following code example describes the CRUD operations handled at server-side.

    public ActionResult Update(OrdersDetails value)
    {
        ...
        return Json(value);
    }
    public ActionResult Insert(OrdersDetails value)
    {
        ...
        return Json(new { data = value });
    }
    public ActionResult Delete(int key)
    {
        ...
        return Json(data);
    }

Custom Adaptor

You can create your own adaptor by extending the built-in adaptors. For the sake of demonstrating custom adaptor approach, we are going to see how to add serial number for the records by overriding the built-in response processing using processResponse method of the ODataAdaptor.

Source
Preview
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridComponent, ColumnsDirective, ColumnDirective } from '@syncfusion/ej2-react-grids';
import { DataManager, ODataAdaptor } from '@syncfusion/ej2-data';

class SerialNoAdaptor extends ODataAdaptor {
    processResponse() {
        let i = 0;
        //calling base class processResponse function
        let original = super.processResponse.apply(this, arguments);
        //Adding serial number
        original.result.forEach((item) => item['Sno'] = ++i);
        return { result: original.result, count: original.count };
    }
}

class App extends React.Component<{}, {}>{
    public data = new DataManager({
                      url: 'https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders/',
                      adaptor: new SerialNoAdaptor
                    });
    render() {
        return <GridComponent dataSource={this.data}>
                <ColumnsDirective>
                    <ColumnDirective field='Sno' headerText='SNO' width='120' textAlign="Right"></ColumnDirective>
                    <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipName' headerText='Ship Name' width='150'></ColumnDirective>
                </ColumnsDirective>
               </GridComponent>
    }
}
ReactDOM.render(<App />, document.getElementById('grid'));

Offline mode

On remote data binding, all grid actions such as paging, sorting, editing, grouping, filtering, etc, will be processed on server-side. To avoid post back for every action, set the grid to load all data on initialization and make the actions process in client-side. To enable this behavior, use the offline property of DataManager.

Source
Preview
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridComponent, ColumnsDirective, ColumnDirective, Inject } from '@syncfusion/ej2-react-grids';
import { DataManager, ODataAdaptor } from '@syncfusion/ej2-data';
import { Page, Sort, Group } from '@syncfusion/ej2-react-grids';

class App extends React.Component<{}, {}>{
    public data = new DataManager({
                      url: 'https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders/',
                      adaptor: new ODataAdaptor,
                      offline: true
                    });
    public page = {pageSize:7};
    render() {
        return <GridComponent dataSource={this.data} allowPaging={true} allowGrouping={true} allowSorting={true} pageSettings={this.page}>
                <Inject services={[Page, Group, Sort]}></Inject>
                <ColumnsDirective>
                    <ColumnDirective field='OrderID' headerText='Order ID' width='120' textAlign="Right"></ColumnDirective>
                    <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipName' headerText='Ship Name' width='150'></ColumnDirective>
                </ColumnsDirective>
               </GridComponent>
    }
}
ReactDOM.render(<App />, document.getElementById('grid'));

Sending additional parameters to server

To add a custom parameter to the data request, use the addParams method of Query class. Assign the Query object with additional parameters to the grid query property.

Source
Preview
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridComponent, ColumnsDirective, ColumnDirective } from '@syncfusion/ej2-react-grids';
import { DataManager, Query, ODataAdaptor } from '@syncfusion/ej2-data';

class App extends React.Component<{}, {}>{
    public data = new DataManager({
                      url: 'https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders/',
                      adaptor: new ODataAdaptor
                    });
    public query = new Query().addParams('ej2grid', 'true');
    render() {
        return <GridComponent dataSource={this.data} query={this.query}>
                <ColumnsDirective>
                    <ColumnDirective field='OrderID' headerText='Order ID' width='120' textAlign="Right"></ColumnDirective>
                    <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipName' headerText='Ship Name' width='150'></ColumnDirective>
                </ColumnsDirective>
               </GridComponent>
    }
}
ReactDOM.render(<App />, document.getElementById('grid'));

The parameters added using the query property will be sent along with the data request for every grid action.

Handle Http Error

During server interaction from the grid, some server-side exceptions may occur, and you can acquire those error messages or exception details in client-side using the actionFailure event.

The argument passed to the actionFailure Grid event contains the error details returned from server.

Source
Preview
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { GridComponent, ColumnsDirective, ColumnDirective } from '@syncfusion/ej2-react-grids';
import { DataManager } from '@syncfusion/ej2-data';

class App extends React.Component<{}, {}>{
    public data = new DataManager({
                      url: 'http://services.odata.org/invalidurl'
                    });
    render() {
        return <GridComponent dataSource={this.data} actionFailure={this.onActionFailure}>
                <ColumnsDirective>
                    <ColumnDirective field='OrderID' headerText='Order ID' width='120' textAlign="Right"></ColumnDirective>
                    <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
                    <ColumnDirective field='ShipName' headerText='Ship Name' width='150'></ColumnDirective>
                </ColumnsDirective>
               </GridComponent>
    }

    onActionFailure(e) {
        let span: Element = document.createElement('span');
        document.getElementById('grid').parentNode.insertBefore(span, document.getElementById('grid'));
        span.style.color = "#FF0000";
        span.innerHTML = "Server exception: 404 Not found";
    }
}
ReactDOM.render(<App />, document.getElementById('grid'));

The actionFailure event will be triggered not only for the server errors, but also when there is an exception while processing the grid actions.

Custom Binding

It is possible to handle data processing externally and bind the result to the grid. This help you to provide your own custom data logic. Grid expects an object as the result of the custom logic and the emitted value should be an object with properties result and count.

In this context, we are going to use Ajax from our @syncfusion/ej2-base library for handling remote interaction, you can choose any HTTP client as per your choice.

import * as ReactDOM from 'react-dom';
import * as React from 'react';
import { Grid, GridComponent, ColumnsDirective, ColumnDirective, DataResult, Sort, Inject, DataStateChangeEventArgs } from '@syncfusion/ej2-react-grids';
import { orderDetails } from './data';
import { SampleBase } from '../common/sample-base';
import { Ajax } from '@syncfusion/ej2-base';


export class CustomBinding extends SampleBase<{}, {}> {
  public orderService: OrderService = new OrderService();
  private grid: Grid;
  public data;
  rendereComplete() {
    let state = { skip: 0, take: 10 };
    this.dataStateChange(state);
  }
  public dataStateChange(state : DataStateChangeEventArgs) {
    this.orderService.execute(state).then(( gridData ) => {this.grid.dataSource = gridData} );
  }
  render() {
    return (
      <div className='control-pane'>
        <div className='control-section'>
          <GridComponent dataSource={this.data} ref={g => this.grid = g} dataStateChange={this.dataStateChange.bind(this)}>
            <ColumnsDirective>
              <ColumnDirective field='OrderID' headerText='Order ID' width='120'></ColumnDirective>
              <ColumnDirective field='CustomerID' headerText='Customer Name' width='150'></ColumnDirective>
              <ColumnDirective field='ShipName' headerText='Ship Name' width='120' />
              <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
            </ColumnsDirective>
            <Inject services={[Page, Group, Sort]} />
          </GridComponent>
        </div>)
  }
}
export class OrderService {

  public ajax: Ajax = new Ajax({
      type: 'GET', mode: true,
      onFailure: (e: Error) => { return false; }
  });

  private BASE_URL: string = 'https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders';

  public execute(state: DataStateChangeEventArgs): Promise<DataResult> {
      return this.getData(state);
  }

  private getData(state: DataStateChangeEventArgs): Promise<DataResult> {

      this.ajax.url = `${this.BASE_URL}?&$inlinecount=allpages&$format=json`;

      return this.ajax.send().then((response: any) => {
          let data: any = JSON.parse(response);
          return { result: data['d']['results'], count: parseInt(data['d']['__count'], 10) };
      });
  }
}

Handling Grid actions

For grid actions such as paging, grouping, sorting etc, the dataStateChange event will be invoked. You have to query and resolve data using AJAX in this event based on the state arguments.

import * as ReactDOM from 'react-dom';
import * as React from 'react';
import { Grid, GridComponent, ColumnsDirective, ColumnDirective, Page, Group, Sorts, DataResult, Sort, Inject, DataStateChangeEventArgs } from '@syncfusion/ej2-react-grids';
import { orderDetails } from './data';
import { SampleBase } from '../common/sample-base';
import { Ajax } from '@syncfusion/ej2-base';


export class CustomBinding extends SampleBase<{}, {}> {
  public orderService: OrderService = new OrderService();
  private grid: Grid;
  public data;
  rendereComplete() {
    let state = { skip: 0, take: 10 };
    this.dataStateChange(state);
  }
  public dataStateChange(state : DataStateChangeEventArgs) {
    this.orderService.execute(state).then(( gridData ) => {this.grid.dataSource = gridData} );
  }
  render() {
    return (
      <div className='control-pane'>
        <div className='control-section'>
          <GridComponent dataSource={this.data} ref={g => this.grid = g} allowPaging={true} allowSorting={true} pageSettings={{ pageCount: 4, pageSize: 10 }} allowGrouping={true} dataStateChange={this.dataStateChange.bind(this)}>
            <ColumnsDirective>
              <ColumnDirective field='OrderID' headerText='Order ID' width='120'></ColumnDirective>
              <ColumnDirective field='CustomerID' headerText='Customer Name' width='150'></ColumnDirective>
              <ColumnDirective field='ShipName' headerText='Ship Name' width='120' />
              <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
            </ColumnsDirective>
            <Inject services={[Page, Group, Sort]} />
          </GridComponent>
        </div>)
  }
}
export class OrderService {

  public ajax: Ajax = new Ajax({
      type: 'GET', mode: true,
      onFailure: (e: Error) => { return false; }
  });

  private BASE_URL: string = 'https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders';

  public execute(state: DataStateChangeEventArgs): Promise<DataResult> {
      return this.getData(state);
  }

  private getData(state: DataStateChangeEventArgs): Promise<DataResult> {
      const pageQuery = `$skip=${state.skip}&$top=${state.take}`;
      let sortQuery: string = '';

      if ((state.sorted || []).length) {
          sortQuery = `&$orderby=` + (state).sorted.map((obj: Sorts) => {
              return obj.direction === 'descending' ? `${obj.name} desc` : obj.name;
          }).reverse().join(',');
      }

      this.ajax.url = `${this.BASE_URL}?${pageQuery}${sortQuery}&$inlinecount=allpages&$format=json`;

      return this.ajax.send().then((response: any) => {
          let data: any = JSON.parse(response);
          return { result: data['d']['results'], count: parseInt(data['d']['__count'], 10) };
      });
  }
}

While initial rendering, the dataStateChange event will not be triggered. You can perform the operation in the componentDidMount or when you want the grid to show record.

Perform CRUD operations

The dataSourceChanged event will be triggered for updating the grid data. You can perform the save operation based on the event arguments and you need to call the endEdit method to indicate the completion of save operation.

import * as ReactDOM from 'react-dom';
import * as React from 'react';
import { Grid, GridComponent, ColumnsDirective, ColumnDirective, Page, Group, Sorts, DataResult, DataSourceChangedEventArgs, Sort, Inject, DataStateChangeEventArgs, Edit } from '@syncfusion/ej2-react-grids';
import { orderDetails } from './data';
import { SampleBase } from '../common/sample-base';
import { Ajax } from '@syncfusion/ej2-base';


export class CustomBinding extends SampleBase<{}, {}> {
  public orderService: OrderService = new OrderService();
  private grid: Grid;
  public data;
  public toolbarOptions: any = ['Add', 'Edit', 'Delete', 'Update', 'Cancel'];
  public editSettings: any = { allowEditing: true, allowAdding: true, allowDeleting: true };
  rendereComplete() {
    let state = { skip: 0, take: 10 };
    this.dataStateChange(state);
  }

  public dataStateChange(state: DataStateChangeEventArgs) {
    this.orderService.execute(state).then((gridData) => { this.grid.dataSource = gridData });
  }

  public dataSourceChanged(state: DataSourceChangedEventArgs): void {
    if (state.action === 'add') {
      this.orderService.addRecord(state).subscribe(() => state.endEdit());
    } else if (state.action === 'edit') {
      this.orderService.updateRecord(state).subscribe(() => state.endEdit());
    } else if (state.requestType === 'delete') {
      this.orderService.deleteRecord(state).subscribe(() => state.endEdit());
    }
  }

  render() {
    return (
      <div className='control-pane'>
        <div className='control-section'>
          <GridComponent dataSource={this.data} ref={g => this.grid = g} editSettings={this.editSettings} toolbar={this.toolbarOptions} allowPaging={true} allowSorting={true} pageSettings={{ pageCount: 4, pageSize: 10 }} allowGrouping={true} dataStateChange={this.dataStateChange.bind(this)}>
            <ColumnsDirective>
              <ColumnDirective field='OrderID' headerText='Order ID' width='120'></ColumnDirective>
              <ColumnDirective field='CustomerID' headerText='Customer Name' width='150'></ColumnDirective>
              <ColumnDirective field='ShipName' headerText='Ship Name' width='120' />
              <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
            </ColumnsDirective>
            <Inject services={[Page, Group, Sort, Filter, Edit]} />
          </GridComponent>
        </div>
    )
  }
}

Calculate aggregates

The footer aggregate values should be calculated and send along with the dataSource property as follows. The aggregate property of the data source should contain the aggregate value assigned to the property named in the field – type format. For example, the Sum aggregate value for the Freight field should be assigned to the property named as Freight - sum.

{
    result: [{..}, {..}, {..}, ...],
    count: 830,
    aggregates: { 'Freight - sum' : 450,'EmployeeID - min': 1 }
}

The group footer and caption aggregate values will be calculated by the grid itself.

Provide Excel filter data source

The dataStateChange event will be triggered with appropriate arguments when the excel filter requests the filter choice data source. You need to resolve the excel filter data source using the dataSource resolver function from the state argument as follows.

import * as ReactDOM from 'react-dom';
import * as React from 'react';
import { Grid, GridComponent, ColumnsDirective, ColumnDirective, Page, Group, Sorts, DataResult, Sort, Inject, DataStateChangeEventArgs } from '@syncfusion/ej2-react-grids';
import { orderDetails } from './data';
import { SampleBase } from '../common/sample-base';
import { Ajax } from '@syncfusion/ej2-base';


export class CustomBinding extends SampleBase<{}, {}> {
  public orderService: OrderService = new OrderService();
  private grid: Grid;
  public filterSettings: any = { type: 'Excel' }
  public data;
  rendereComplete() {
    let state = { skip: 0, take: 10 };
    this.dataStateChange(state);
  }
  public dataStateChange(state : DataStateChangeEventArgs) {
    if (state.action.requestType === "filterchoicerequest" || state.action.requestType ==="filtersearchbegin") {
      this.orderService.execute(state).then((e) => state.dataSource(e));
    } else {
      this.orderService.execute(state).then(( gridData ) => {this.grid.dataSource = gridData} );
    }
  }
  render() {
    return (
      <div className='control-pane'>
        <div className='control-section'>
          <GridComponent dataSource={this.data} ref={g => this.grid = g} allowPaging={true} allowSorting={true} pageSettings={{ pageCount: 4, pageSize: 10 }} allowGrouping={true} dataStateChange={this.dataStateChange.bind(this)} filterSettings={this.filterSettings}>
            <ColumnsDirective>
              <ColumnDirective field='OrderID' headerText='Order ID' width='120'></ColumnDirective>
              <ColumnDirective field='CustomerID' headerText='Customer Name' width='150'></ColumnDirective>
              <ColumnDirective field='ShipName' headerText='Ship Name' width='120' />
              <ColumnDirective field='ShipCity' headerText='Ship City' width='150'></ColumnDirective>
            </ColumnsDirective>
            <Inject services={[Page, Group, Sort]} />
          </GridComponent>
        </div>)
  }
}

Binding with ajax

You can use Grid dataSource property to bind the datasource to Grid from external ajax request. In the below code we have fetched the datasource from the server with the help of ajax request and provided that to [dataSource][`datasource`](../../api/grid/#datasource) property by using onSuccess event of the ajax.

import * as React from 'react';
import { render } from 'react-dom';
import { GridComponent, ColumnsDirective, ColumnDirective } from '@syncfusion/ej2-react-grids';
import { SampleBase } from './sample-base';
import { Ajax } from '@syncfusion/ej2-base';

export class Default extends React.Component {
  componentDidMount(){
    let grid = this.gridInstance; // Grid instance
    let ajax = new Ajax("https://ej2services.syncfusion.com/production/web-services/api/Orders", "GET");
    ajax.send();
    ajax.onSuccess = function(data){
      grid.dataSource = JSON.parse(data);
    }
  }
    render() {
        return (<div className='control-pane'>
        <div className='control-section'>
          <GridComponent ref={grid => this.gridInstance = grid}>
            <ColumnsDirective>
              <ColumnDirective field='OrderID' headerText='Order ID'  textAlign='Right' width='120'></ColumnDirective>
              <ColumnDirective field='CustomerID' headerText='Customer ID'  textAlign='Right'  width='120'></ColumnDirective>
              <ColumnDirective field='EmployeeID' headerText='Employee ID'  textAlign='Right'  width='120'></ColumnDirective>
              <ColumnDirective field='ShipCountry' headerText='Ship Country'  textAlign='Right'  width='120'></ColumnDirective>
            </ColumnsDirective>
          </GridComponent>
        </div>
      </div>);
    }
}
render(<Default />, document.getElementById('sample'));
  • If you bind the dataSource from this way, then it acts like a local dataSource. So you cannot perform any server side crud actions.