Search results

Data Binding in React Grid component

18 May 2022 / 11 minutes to read

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

To get start quickly with Data Binding, you can check on this video:

Sending additional parameters to the 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
App.jsx
App.tsx
Copied to clipboard
import { DataManager, ODataAdaptor, Query } from '@syncfusion/ej2-data';
import { ColumnDirective, ColumnsDirective, GridComponent } from '@syncfusion/ej2-react-grids';
import * as React from 'react';
export default class App extends React.Component {
    constructor() {
        super(...arguments);
        this.data = new DataManager({
            adaptor: new ODataAdaptor,
            url: 'https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders/'
        });
        this.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 field='CustomerID' headerText='Customer ID' width='150'/>
                <ColumnDirective field='ShipCity' headerText='Ship City' width='150'/>
                <ColumnDirective field='ShipName' headerText='Ship Name' width='150'/>
            </ColumnsDirective>
           </GridComponent>;
    }
}
Copied to clipboard
import { DataManager, ODataAdaptor, Query } from '@syncfusion/ej2-data';
import { ColumnDirective, ColumnsDirective, GridComponent } from '@syncfusion/ej2-react-grids';
import * as React from 'react';

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

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

Handling 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
App.jsx
App.tsx
Copied to clipboard
import { DataManager } from '@syncfusion/ej2-data';
import { ColumnDirective, ColumnsDirective, GridComponent } from '@syncfusion/ej2-react-grids';
import * as React from 'react';
export default class App extends React.Component {
    constructor() {
        super(...arguments);
        this.data = new DataManager({
            url: 'http://services.odata.org/invalidurl'
        });
        this.onActionFailure = (e) => {
            const span = document.createElement('span');
            if (this.grid) {
                this.grid.element.parentNode.insertBefore(span, this.grid.element);
                span.style.color = "#FF0000";
                span.innerHTML = "Server exception: 404 Not found";
            }
        };
    }
    render() {
        this.onActionFailure = this.onActionFailure.bind(this);
        return <GridComponent dataSource={this.data} ref={g => this.grid = g} actionFailure={this.onActionFailure}>
            <ColumnsDirective>
                <ColumnDirective field='OrderID' headerText='Order ID' width='120' textAlign="Right"/>
                <ColumnDirective field='CustomerID' headerText='Customer ID' width='150'/>
                <ColumnDirective field='ShipCity' headerText='Ship City' width='150'/>
                <ColumnDirective field='ShipName' headerText='Ship Name' width='150'/>
            </ColumnsDirective>
           </GridComponent>;
    }
}
Copied to clipboard
import { DataManager } from '@syncfusion/ej2-data';
import { ColumnDirective, ColumnsDirective, FailureEventArgs, Grid, GridComponent } from '@syncfusion/ej2-react-grids';
import * as React from 'react';

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

public onActionFailure = (e: FailureEventArgs) => {
    const span: HTMLElement = document.createElement('span');
    if (this.grid) {
        (this.grid.element.parentNode as HTMLElement).insertBefore(span, this.grid.element);
        span.style.color = "#FF0000";
        span.innerHTML = "Server exception: 404 Not found";
    }
}
}

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

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 property by using onSuccess event of the ajax.

Copied to clipboard
import { Ajax } from '@syncfusion/ej2-base';
import { ColumnDirective, ColumnsDirective, Grid, GridComponent } from '@syncfusion/ej2-react-grids';
import * as React from 'react';

export default class App extends React.Component<{}, {}> {
  public grid: Grid | null;
  public componentDidMount(){
const ajax = new Ajax("https://ej2services.syncfusion.com/production/web-services/api/Orders", "GET");
ajax.send();
ajax.onSuccess = (data: any) => {
  if (this.grid) {
    this.grid.dataSource = JSON.parse(data);
  }
}
  }
public render() {
    return (<div className='control-pane'>
    <div className='control-section'>
      <GridComponent ref={g => this.grid = g}>
        <ColumnsDirective>
          <ColumnDirective field='OrderID' headerText='Order ID'  textAlign='Right' width='120'/>
          <ColumnDirective field='CustomerID' headerText='Customer ID'  textAlign='Right'  width='120'/>
          <ColumnDirective field='EmployeeID' headerText='Employee ID'  textAlign='Right'  width='120'/>
          <ColumnDirective field='ShipCountry' headerText='Ship Country'  textAlign='Right'  width='120'/>
        </ColumnsDirective>
      </GridComponent>
    </div>
  </div>);
}  
};

If you bind the dataSource from this way, then it acts like a local dataSource. So you cannot perform any server side crud 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.

Copied to clipboard
import { Ajax, getValue } from '@syncfusion/ej2-base';
import { ColumnDirective, ColumnsDirective, DataStateChangeEventArgs, Grid, GridComponent } from '@syncfusion/ej2-react-grids';
import { Inject, Page, PageSettingsModel } from '@syncfusion/ej2-react-grids';
import { DataResult } from '@syncfusion/ej2-react-grids';
import * as React from 'react';

export default class App extends React.Component<{}, {}> {
public orderService: OrderService = new OrderService();
public grid: Grid | null;
public data: any;
public pageSettings: PageSettingsModel = { pageSize: 10 };
public renderComplete() {
    if(this.grid && (this.grid.dataSource instanceof Array
        && !(this.grid.dataSource as object[]).length)) {
        const state = { skip: 0, take: 10 };
        this.dataStateChange(state);
    }
}
public dataStateChange(state : DataStateChangeEventArgs) {
  this.orderService.execute(state).then(( gridData ) => {
      if(this.grid) {
        this.grid.dataSource = gridData
      }
    });
}
public render() {
  this.renderComplete = this.renderComplete.bind(this);
  this.dataStateChange = this.dataStateChange.bind(this);
  return (
    <div className='control-pane'>
      <div className='control-section'>
        <GridComponent dataSource={this.data} ref={g => this.grid = g} pageSettings={this.pageSettings}
          dataBound={this.renderComplete} dataStateChange={this.dataStateChange} allowPaging={true}>
          <ColumnsDirective>
            <ColumnDirective field='OrderID' headerText='Order ID' width='120'/>
            <ColumnDirective field='CustomerID' headerText='Customer Name' width='150'/>
            <ColumnDirective field='ShipName' headerText='Ship Name' width='120' />
            <ColumnDirective field='ShipCity' headerText='Ship City' width='150'/>
          </ColumnsDirective>
          <Inject services={[Page]} />
        </GridComponent>
      </div>
    </div>)
}
  };

  export class OrderService {
public ajax: Ajax = new Ajax({
    mode: true,
    onFailure: (e: Error) => false,
    type: 'GET'
});
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}`;
    this.ajax.url = `${this.BASE_URL}?${pageQuery}&$inlinecount=allpages&$format=json`;

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

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.

Copied to clipboard
import { Ajax, getValue } from '@syncfusion/ej2-base';
import { ColumnDirective, ColumnsDirective, DataStateChangeEventArgs, Grid, GridComponent } from '@syncfusion/ej2-react-grids';
import { Group, Inject, Page, PageSettingsModel, Sort } from '@syncfusion/ej2-react-grids';
import { DataResult, Sorts } from '@syncfusion/ej2-react-grids';
import * as React from 'react';


export default class App extends React.Component<{}, {}> {
public orderService: OrderService = new OrderService();
public grid: Grid | null;
public data: any;
public pageSettings: PageSettingsModel = { pageSize: 10 };
public renderComplete() {
    if(this.grid && (this.grid.dataSource instanceof Array
        && !(this.grid.dataSource as object[]).length)) {
        const state = { skip: 0, take: 10 };
        this.dataStateChange(state);
    }
}
public dataStateChange(state : DataStateChangeEventArgs) {
  this.orderService.execute(state).then(( gridData ) => {
      if(this.grid) {
        this.grid.dataSource = gridData
      }
    });
}
public render() {
  this.renderComplete = this.renderComplete.bind(this);
  this.dataStateChange = this.dataStateChange.bind(this);
  return (
    <div className='control-pane'>
      <div className='control-section'>
        <GridComponent dataSource={this.data} ref={g => this.grid = g} pageSettings={this.pageSettings}
          dataBound={this.renderComplete} dataStateChange={this.dataStateChange} allowPaging={true}
          allowGrouping={true} allowSorting={true}>
          <ColumnsDirective>
            <ColumnDirective field='OrderID' headerText='Order ID' width='120'/>
            <ColumnDirective field='CustomerID' headerText='Customer Name' width='150'/>
            <ColumnDirective field='ShipName' headerText='Ship Name' width='120' />
            <ColumnDirective field='ShipCity' headerText='Ship City' width='150'/>
          </ColumnsDirective>
          <Inject services={[Page, Sort, Group]} />
        </GridComponent>
      </div>
    </div>)
}
  };

export class OrderService {
public ajax: Ajax = new Ajax({
    mode: true,
    onFailure: (e: Error) => false,
    type: 'GET'
});
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 && (state.sorted || []).length) {
        sortQuery = `&$orderby=` + ((state).sorted as Sorts[]).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) => {
        const data: any = JSON.parse(response);
        return {
            count:  parseInt(getValue('d.__count', data), 10),
            result: getValue('d.results', data)
        };
    });
}
  };

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 call the endEdit method to indicate the completion of save operation.

Copied to clipboard
import { Ajax, getValue } from '@syncfusion/ej2-base';
import { ColumnDirective, ColumnsDirective, DataStateChangeEventArgs, Grid, GridComponent } from '@syncfusion/ej2-react-grids';
import { DataResult, DataSourceChangedEventArgs, Edit, Inject, Page, PageSettingsModel, Toolbar } from '@syncfusion/ej2-react-grids';
import * as React from 'react';

export default class App extends React.Component<{}, {}> {
public orderService: OrderService = new OrderService();
public grid: Grid | null;
public data: any;  
public toolbarOptions: any = ['Add', 'Edit', 'Delete', 'Update', 'Cancel'];
public editSettings: any = { allowEditing: true, allowAdding: true, allowDeleting: true };
  
public pageSettings: PageSettingsModel = { pageSize: 10 };
public renderComplete() {
    if(this.grid && (this.grid.dataSource instanceof Array
        && !(this.grid.dataSource as object[]).length)) {
        const state = { skip: 0, take: 10 };
        this.dataStateChange(state);
    }
}
public dataStateChange(state : DataStateChangeEventArgs) {
  this.orderService.execute(state).then(( gridData ) => {
    if (this.grid) {
        this.grid.dataSource = gridData
    }
  });
}
public dataSourceChanged(state: DataSourceChangedEventArgs): void {
  if (state.action === 'add') {
    this.orderService.addRecord(state).then(() => state.endEdit());
  } else if (state.action === 'edit') {
    this.orderService.updateRecord(state).then(() => state.endEdit());
  } else if (state.requestType === 'delete') {
    this.orderService.deleteRecord(state).then(() => state.endEdit());
  }
}
  
public render() {
  this.dataStateChange = this.dataStateChange.bind(this);
  this.dataSourceChanged = this.dataSourceChanged.bind(this);
  this.renderComplete = this.renderComplete.bind(this);
  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={this.pageSettings}
          allowGrouping={true} dataStateChange={this.dataStateChange}
          dataSourceChanged={this.dataSourceChanged} dataBound={this.renderComplete}>
          <ColumnsDirective>
            <ColumnDirective field='OrderID' headerText='Order ID' width='120'/>
            <ColumnDirective field='CustomerID' headerText='Customer Name' width='150'/>
            <ColumnDirective field='ShipName' headerText='Ship Name' width='120' />
            <ColumnDirective field='ShipCity' headerText='Ship City' width='150'/>
          </ColumnsDirective>
          <Inject services={[Page, Edit, Toolbar]} />
        </GridComponent>
      </div>
    </div>
  )
}
  };
  
export class OrderService {
public ajax: Ajax = new Ajax({
    mode: true,
    onFailure: (e: Error) => false,
    type: 'GET'
});
private BASE_URL: string = '/api/Orders';
  
public execute(state: DataStateChangeEventArgs): Promise<DataResult> {
    return this.getData(state);
}
public addRecord(state: DataSourceChangedEventArgs) : Promise<DataResult> {
    const add: Ajax = new Ajax({
        mode: true,
        onFailure: (e: Error) => false,
        type: 'POST'
    });
    return add.send(JSON.stringify(state.data)).then((response: any) => {
        const data: any = JSON.parse(response);
        return data;
    });
}
public updateRecord(state: DataSourceChangedEventArgs) : Promise<DataResult> {
    const update: Ajax = new Ajax({
        mode: true,
        onFailure: (e: Error) => false,
        type: 'PUT'
    });
    return update.send(JSON.stringify(state.data)).then((response: any) => {
        const data: any = JSON.parse(response);
        return data;
    });
}
public deleteRecord(state: DataSourceChangedEventArgs) : Promise<DataResult> {
    const remove: Ajax = new Ajax({
        mode: true,
        onFailure: (e: Error) => false,
        type: 'DELETE'
    });
    return remove.send(JSON.stringify((state.data && state.data[0]))).then((response: any) => {
        const data: any = JSON.parse(response);
        return data;
    });
}
private getData(state: DataStateChangeEventArgs): Promise<DataResult> {
    const pageQuery = state.skip ? `$skip=${state.skip}&$top=${state.take}` : `$top=${state.take}`;
    this.ajax.url = `${this.BASE_URL}?${pageQuery}&$inlinecount=allpages&$format=json`;
  
    return this.ajax.send().then((response: any) => {
        const data: any = JSON.parse(response);
        return {
            count:  parseInt(getValue('d.__count', data), 10),
            result: getValue('d.results', data)
        };
    });
}
  };

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.

Copied to clipboard
{
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.

Copied to clipboard
import { ColumnDirective, ColumnsDirective, DataStateChangeEventArgs, Grid, GridComponent } from '@syncfusion/ej2-react-grids';
import { Filter, FilterSettingsModel, Inject, Page, PageSettingsModel } from '@syncfusion/ej2-react-grids';
import * as React from 'react';
import { OrderService } from './OrderService';

export default class App extends React.Component<{}, {}> {
public orderService: OrderService = new OrderService();
public grid: Grid | null;
public data: any;
public filterSettings: FilterSettingsModel = { type: 'Excel' }
public pageSettings: PageSettingsModel = { pageSize: 10 };
public renderComplete() {
    if(this.grid && (this.grid.dataSource instanceof Array
        && !(this.grid.dataSource as object[]).length)) {
        const state = { skip: 0, take: 10 };
        this.dataStateChange(state);
    }
}
public dataStateChange(state : DataStateChangeEventArgs) {
    if (state.action && (state.action.requestType === 'filterchoicerequest'
        || state.action.requestType ==='filtersearchbegin')) {
      this.orderService.execute(state).then((e) => state.dataSource && state.dataSource(e));
    } else {
      this.orderService.execute(state).then(( gridData ) => {
        if (this.grid) {
            this.grid.dataSource = gridData
        }
      });
    }
}
public render() {
  this.renderComplete = this.renderComplete.bind(this);
  this.dataStateChange = this.dataStateChange.bind(this);
  return (
    <div className='control-pane'>
      <div className='control-section'>
        <GridComponent dataSource={this.data} ref={g => this.grid = g} allowFiltering={true} allowPaging={true}
            pageSettings={{ pageCount: 4, pageSize: 10 }} dataStateChange={this.dataStateChange}
            dataBound={this.renderComplete} filterSettings={this.filterSettings}>
          <ColumnsDirective>
            <ColumnDirective field='OrderID' headerText='Order ID' width='120'/>
            <ColumnDirective field='CustomerID' headerText='Customer Name' width='150'/>
            <ColumnDirective field='ShipName' headerText='Ship Name' width='120' />
            <ColumnDirective field='ShipCity' headerText='Ship City' width='150'/>
          </ColumnsDirective>
          <Inject services={[Page, Filter]} />
        </GridComponent>
      </div>
    </div>)
}
  };

See Also