DEV Community

Shanika Wickramasinghe
Shanika Wickramasinghe

Posted on • Originally published at Medium

jQwidgets Grid with React Features

React is a light-weighted library, which is widely used for UI/UX designs of web pages. It provides one of the responsive and flexible grids which display the data in tabular form using jQWidgets.

This article covers the basic steps to create a jQWidgets grid for React using typescript.

Installation of React:

React is an interactive library which renders the right components while the data changes. To install React we will first need to install node.js 8.10 or later versions. Check for node.js and npm versions.

Create React App:

Using npm we will create an application for React as given below. This creates the folder structure and the directory called my-app. Once my-app is created, cd to my-app and type npm start. The project opens in http://localhost:3000.

npm i -g create-jqwidgets-react-app
npx create-jqwidgets-react-app my-app --typescript
cd my-app
npm install jqwidgets-script –save--dev
npm start
Enter fullscreen mode Exit fullscreen mode

The folder structure is as below:

Create a Simple jQWidgets Grid Component for React:

Once the required folders and files are created we will work on the settings and imports needed for jQWidgets grid component of React.

App.htm file:

We will add the below links to the section of App.html page.

<link rel="canonical" href="https://www.jqwidgets.com/react/react-grid/" />
<link rel="stylesheet" href="../jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="../scripts/demos.js"></script>
<script src="./../node_modules/react/umd/react.production.min.js"></script>
<script src="./../node_modules/react-dom/umd/react-dom.production.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

App.tsx file:

In App.tsx file we will first import jqxGrid from jqwidgets-react. This will provide the jqxGrid component created for React library. We will use a few CSS files for styling the grid.

import 'jqwidgets-scripts/jqwidgets/styles/jqx.base.css';
import 'jqwidgets-scripts/jqwidgets/styles/jqx.material-purple.css';
import JqxGrid, { IGridProps, jqx } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxgrid';
Enter fullscreen mode Exit fullscreen mode

Next, we will create the App class using jqxGrid, we will first construct the properties by setting the grid with source properties like data field, datatype, id, record, etc. Later we will set the state for this grid.

export class App extends React.PureComponent<{}, IGridProps> {
    constructor(props: {}) {
        super(props);
        const source: any = {
            datafields: [
                { name: 'Name', type: 'string' },
                { name: 'Sex'  , type: 'string' },
                { name: 'City', type: 'string' },
                { name: 'Address', type: 'string },
            ],
            datatype: 'xml',    
            id: 'NameID',
            record: 'Name',
            root: 'Name',
            url: './../sampledata/Details.xml'
        };  
//set the state for widget.
    this.state = {
        columns: [
            { text: 'Name', datafield: 'Name', width: 250 },
            { text: 'Sex', datafield: 'Sex', width: 100 },
            { text: 'City', datafield: 'City', width: 80 },                                                      { text: 'Address', datafield: 'Address', width: 350 },
        ],
        source: new jqx.dataAdapter(source)
    }
}
public render() {
    return (
        <JqxGrid
        // @ts-ignore
            width={this.state.width} source={this.state.source} columns={this.state.columns} autoheight={true} altrows={true}
        } />
      )
    }  
}
Enter fullscreen mode Exit fullscreen mode

After you define all your properties and state to the grid we will render this component using the render(). Once you run this sample example your grid would look like below.

Grid Features for React:

jQWidgets Data Grid for React is built for professional use with features like sorting, filtering, grouping, paging, editing, drag-drop, nested grids, etc. Before we will look into how to enable these features for better user experience, we need to add bundle.js files for respective features in App.html eg: adding bundle files for sorting in App.htm file

<div id="app"></div>
<script src="../dist/grid_sorting.bundle.js"></script>
Enter fullscreen mode Exit fullscreen mode

Sorting:

The sortable property enables or disables the data sorting. In the code example below, the Grid data sorting is enabled:

<JqxGrid ref={this.myGrid} onSort={this.myGridOnSort}
    width={getWidth('grid')} height={450} source={this.state.source} columns={this.state.columns} sortable={true} altrows={true} filterable={true} selectionmode={'multiplecellsadvanced'} />
</JqxGrid>
Enter fullscreen mode Exit fullscreen mode

To enable or disable the sorting of a Grid column, you can set its sortable property to false. Also when the sorting data type is Date, Number or Boolean, the 'type' property in the 'datafield' array should be set.
The 'sortcolumn' property specifies the default Grid sort column, i.e. when the grid is displayed, the data will be sorted. The 'sortdirection' property specifies the sort order of the sort column.

sortcolumn: 'ColumnName',
sortdirection: 'asc'
Enter fullscreen mode Exit fullscreen mode

The “sortby” function can be used to sort the Grid through the API. This function should be called when the grid data is fully loaded. The first parameter is the Column's DataField. The second parameter is the sort order - 'asc' or 'desc'.

Filtering:

To enable the filtering feature, you need to set the 'filterable' property to true. When the value of the filterable property is true, the grid displays a filtering panel in the columns popup menus. Filtering can be done in background or can be customized.

<JqxGrid ref={this.myGrid} onFilter={this.onFilter}
     width={getWidth('grid')} source={this.state.source} columns={this.state.columns}
    filterable={true} sortable={true} ready={this.state.ready} autoshowfiltericon={true} />
Enter fullscreen mode Exit fullscreen mode

Grid Grouping:

The jqxGrid component supports data grouping against one or more columns. Grouping is allowed if the 'groupable' property is set to true. End-users can group data by dragging the column headers to the Group Panel.
The code example below shows a Grid template with one grouping column:

<JqxGrid ref={this.myGrid}
    onGroupexpand={this.onGroupExpand} onGroupcollapse={this.onGroupCollapse}
                    // @ts-ignore
    width={getWidth('grid')} groupable={true} columns={this.state.columns}
    source={this.state.source} groups={['Country']} />
Enter fullscreen mode Exit fullscreen mode

Grid Paging:

The built-in paging capability gives an additional edge to display a large amount of data in tabular format. The pageable property is set to true, to make the paging available.

<JqxGrid ref={this.myGrid}
    onPagechanged={this.onPageChanged}  onPagesizechanged={this.onPageSizeChanged}
          // @ts-ignore
          width={getWidth('grid')} source={this.state.source}   columns={this.state.columns}
          pageable={true} sortable={true} columnsresize={true}
          autoheight={true} selectionmode={'multiplerowsextended'} />
Enter fullscreen mode Exit fullscreen mode

Pagechanged or pagesizechanged events are raised when the page is changed or page size is changed.

private onPageChanged(event: any): void {
        this.eventsLog.current!.style.display = 'block';
        const loggedElements = document.getElementsByClassName('logged');
        if (loggedElements.length >= 5) {
            this.myPanel.current!.clearcontent();
        }
        const args = event.args;
        const eventData = 'pagechanged <div>Page:' + args.pagenum + ', Page Size: ' + args.pagesize + '</div>';
        this.myPanel.current!.prepend('<div class="logged" style="margin-top: 5px;">' + eventData + '</div>');
        // get page information.
        const paginginformation = this.myGrid.current!.getpaginginformation();
        this.pagingInfo.current!.innerHTML = '<div style="margin-top: 5px;">Page:' + paginginformation.pagenum + ', Page Size: ' + paginginformation.pagesize + ', Pages Count: ' + paginginformation.pagescount + '</div>';
    }
    private onPageSizeChanged(event: any): void {
        this.eventsLog.current!.style.display = 'block';
        this.myPanel.current!.clearcontent();
        const args = event.args;
        const eventData = 'pagesizechanged <div>Page:' + args.pagenum + ', Page Size: ' + args.pagesize + ', Old Page Size: ' + args.oldpagesize + '</div>';
        this.myPanel.current!.prepend('<div style="margin-top: 5px">' + eventData + '</div>');
        // get page information.
        const paginginformation = this.myGrid.current!.getpaginginformation();
        this.pagingInfo.current!.innerHTML = '<div style="margin-top: 5px;">Page:' + paginginformation.pagenum + ', Page Size: ' + paginginformation.pagesize + ', Pages Count: ' + paginginformation.pagescount + '</div>';
    }
Enter fullscreen mode Exit fullscreen mode

The grid paging also displays the drop-down list component in the pager area. By default, the size options are 5, 10 and 20. The "pager" property enables you to set different modes to display the pagination for a grid. You have two modes for “pager” settings, default and simple.

Grid Cell Editing:

Grid cell editing is one of the important features for interactiveness of the grid. This feature resembles the data entering experience in an Excel Spreadsheet – once you select a grid cell, you can enter data when you start typing text. The Grid's 'editable' property specifies whether the editing is enabled or not.
The Grid has APIs for showing and hiding the cell editors. The ‘cellBeginEditEvent’ method allows you to put a specific cell into edit mode.

this.cellBeginEditEvent = this.cellBeginEditEvent.bind(this);
this.cellEndEditEvent = this.cellEndEditEvent.bind(this);
Enter fullscreen mode Exit fullscreen mode

The ‘cellEndEditEvent’ method ends the edit operation and confirms or cancels the changes.

public render() {
        return (
            <div>
                <JqxGrid onCellbeginedit={this.cellBeginEditEvent} onCellendedit={this.cellEndEditEvent}
                    // @ts-ignore
                    width={getWidth('grid')} source={this.state.source} columns={this.state.columns}
                    editable={true} enabletooltips={true} selectionmode={'multiplecellsadvanced'} />
                <div style={{ fontSize: '12px', fontFamily: 'Verdana', marginTop: '30px' }}>
                    <div ref={this.beginEdit} />
                    <div ref={this.endEdit} style={{ marginTop: '10px' }} />
                </div>
            </div>
        );
    }
    private cellBeginEditEvent(event: any): void {
        const args = event.args;
        this.beginEdit.current!.innerHTML = 'Event Type: cellbeginedit, Column: ' + args.datafield + ', Row: ' + (1 + args.rowindex) + ', Value: ' + args.value;
    }
    private cellEndEditEvent(event: any): void {
        const args = event.args;
        this.endEdit.current!.innerHTML = 'Event Type: cellendedit, Column: ' + args.datafield + ', Row: ' + (1 + args.rowindex) + ', Value: ' + args.value;
    }
Enter fullscreen mode Exit fullscreen mode

To confirm the edit mode, we will have to press the Esc key. The grid can be customized to display the validation popup message when the new cell's value is not valid for any column or grid.

Summary:

jQWidgets grid for React is a very flexible and powerful tool to allow you to add lots of data with multiple pages. This article demonstrates the basic steps to create the jQWidgets grid for React using typescript. We have also discussed a few interactive features which are basic and are needed for UI of any website. There are a lot more features of the grid, you will have to explore a bit of these features and use the best needed for the UI/ UX design of your page.

Top comments (0)