Skip to content

Discussion on #Grid/Overview #20

@suthatd444

Description

@suthatd444

Type Your Comment Here

class component is very difficult for many developers out there here is function component version of app.jsx

import '@grapecity/wijmo.styles/wijmo.css';
import * as React from 'react';
import '@grapecity/wijmo.touch';
import * as wjCore from '@grapecity/wijmo';
import { InputDate, InputTime } from '@grapecity/wijmo.input';
import { CellMaker, SparklineMarkers } from '@grapecity/wijmo.grid.cellmaker';
import { DataMap } from '@grapecity/wijmo.grid';
import { FlexGrid, FlexGridColumn, FlexGridCellTemplate } from '@grapecity/wijmo.react.grid';
import { FlexGridFilter } from '@grapecity/wijmo.react.grid.filter';
import { FlexGridSearch } from '@grapecity/wijmo.react.grid.search';
import { GroupPanel as FlexGridGroupPanel } from '@grapecity/wijmo.react.grid.grouppanel';
import { DataService, Country, KeyValue } from './data';
import { ExportService } from './export';
interface myrow {
id: any;
date: Date;
time: Date;
countryId: number;
productId: number;
colorId: number;
price: number;
change: number;
history: number[];
discount: number;
rating: number;
active: boolean;
size: number;
weight: number;
quantity: number;
description: string;
}
export default function LSpAdvance() {
let theGrid = React.useRef(null);
let theSearch = React.useRef(null);
const dataService = new DataService;
const exportService = new ExportService
const [table, setStateTable] = React.useState<myrow[]>([]);
const [state, setState] = React.useState({
itemsCount: 500,
flex: {},
isExcelPreparing: false,
isExcelExporting: false,
excelProgress: 0,
});
//
const countryCellTemplate = (ctx) => {
const country = countryMap.getDataItem(ctx.item.countryId) || Country.NotFound;
return (<React.Fragment>
<span className={flag-icon flag-icon-${country.flag}} >
{country.name}

</React.Fragment>);
};
//
const colorCellTemplate = (ctx) => {
const color = (colorMap.getDataItem(ctx.item.colorId) || KeyValue.NotFound).value;
return (<React.Fragment>
<span className="color-tile" style={{ background: color }} >
{color}

</React.Fragment>);
};
//
const changeCellTemplate = (ctx) => {
const change = ctx.item.change;
let cssClass = '';
let displayValue = '';
if (wjCore.isNumber(change)) {
if (change > 0) {
cssClass = 'change-up';
}
else if (change < 0) {
cssClass = 'change-down';
}
displayValue = wjCore.Globalize.formatNumber(change, 'c');
}
else if (!wjCore.isUndefined(change) && change !== null) {
displayValue = wjCore.changeType(change, wjCore.DataType.String);
}
return (
{displayValue}
);
};
//
const gridInitialized = (ctl) => {
let tempdata = createItemsSource(state.itemsCount);
setState({
...state,
flex: { itemsSource: tempdata }
})
};
//
const itemsCountChanged = (e) => {
setState({
...state,
itemsCount: parseInt(e.target.value),
flex: { itemsSource: createItemsSource(state.itemsCount) }
})
lastId = state.itemsCount;
};
//

const resetState = () => setState({
...state,
isExcelPreparing: false,
isExcelExporting: false,
excelProgress: 0,
})

const exportToExcel = () => {

let mstate = {
  itemsCount: 500,
  flex: {},
  isExcelPreparing: false,
  isExcelExporting: false,
  excelProgress: 0,
};
setState(mstate)

const { isExcelPreparing: preparing, isExcelExporting: exporting } = state;


if (!preparing && !exporting) {
  setState({
    ...state,
    isExcelPreparing: true
  })

  exportService.startExcelExport(state.flex, () => {
    console.log('Export to Excel completed');
    resetState();
  }, err => {
    console.error(`Export to Excel failed: ${err}`);
    resetState();
  }, prg => {
    setState({
      ...state,
      isExcelPreparing: false,
      isExcelExporting: true,
      excelProgress: prg,
    })
  });
  console.log('Export to Excel started');
}
else {
  exportService.cancelExcelExport(progress => {
    console.log('Export to Excel canceled');
    resetState();
  });
}

};
//
const exportToPdf = () => {
exportService.exportToPdf(state.flex, {
countryMap: countryMap,
colorMap: colorMap,
historyCellTemplate: historyCellTemplate
});
};
const buildDataMap = (items) => {
let imap = items.map((row, index) => {
return { key: index, value: row };
});
return new DataMap(imap, 'key', 'value');
}

let lastId = state.itemsCount;
// initializes data maps

const productMap = buildDataMap(dataService.getProducts());
const countryMap = new DataMap(dataService.getCountries(), 'id', 'name');
const colorMap = buildDataMap(dataService.getColors());
console.log("countryMap", countryMap);
// initialize editors
const dateEditor = new InputDate(document.createElement('div'), {
format: 'MM/dd/yyyy',
isRequired: false
});
const timeEditor = new InputTime(document.createElement('div'), {
format: 'HH:mm',
isRequired: false
});
// initializes cell templates
const historyCellTemplate = CellMaker.makeSparkline({
markers: SparklineMarkers.High | SparklineMarkers.Low,
maxPoints: 25,
label: 'price history',
});
const ratingCellTemplate = CellMaker.makeRating({
range: [1, 5],
label: 'rating'
});

//
React.useEffect(() => {
gridInitialized("sd");
// connect search box and grid
// if (theGrid.current) {
// theGrid = theGrid.current?.control;
// theSearch = theSearch?.current.control;
// theSearch.grid = theGrid;
// }
}, []);

React.useEffect(() => {
exportService.cancelExcelExport();
}, [])

const createItemsSource = (counter) => {
const data = dataService.getData(counter);
setStateTable(data);
console.log("data", data);
const view = new wjCore.CollectionView(data, {
getError: (item, prop) => {
console.log("propproppropprop", prop);
// const displayName = state?.flex?.columns.getColumn(prop).header;
const displayName = "";
return dataService.validate(item, prop, displayName);
}
});
view.collectionChanged.addHandler((s, e) => {
// initializes new added item with a history data
if (e.action === wjCore.NotifyCollectionChangedAction.Add) {
e.item.history = dataService.getHistoryData();
e.item.id = lastId;
lastId++;
}
});

return view;

}

return (





  <div className="toolbar-item col-sm-3 col-md-3">
    <div className="input-group">
      <span className="input-group-addon">Items:</span>
      <select className="form-control" value={state.itemsCount} onChange={itemsCountChanged}>
        <option value="5">5</option>
        <option value="50">50</option>
        <option value="500">500</option>
        <option value="5000">5,000</option>
        <option value="50000">50,000</option>
        <option value="100000">100,000</option>
      </select>
    </div>
  </div>

  <div className="toolbar-item col-sm-3 col-md-2">
    <button className="btn btn-default btn-block" disabled={state.isExcelPreparing} onClick={exportToExcel}>
      {state.isExcelExporting ? `Cancel (${state.excelProgress}% done)` : 'Export To Excel'}
    </button>
  </div>

  <div className="toolbar-item col-sm-3 col-md-2">
    <button className="btn btn-default btn-block" onClick={exportToPdf}>Export To PDF</button>
  </div>
</div>

<FlexGridGroupPanel grid={state.flex} placeholder={"Drag columns here to create groups"} />
<FlexGrid itemsSource={table} autoGenerateColumns={false} allowAddNew allowDelete allowPinning="SingleColumn" newRowAtTop showMarquee selectionMode="MultiRange" validateEdits={false} initialized={gridInitialized}>
  <FlexGridFilter />
  <FlexGridColumn header="ID" binding="id" width={70} isReadOnly={true} />
  <FlexGridColumn header="Date" binding="date" format="MMM d yyyy" isRequired={false} width={130} editor={dateEditor}>
  </FlexGridColumn>
  <FlexGridColumn header="Country" binding="countryId" dataMap={countryMap} width={145}>
    <FlexGridCellTemplate cellType="Cell" template={countryCellTemplate} />
  </FlexGridColumn>
  <FlexGridColumn header="Price" binding="price" format="c" isRequired={false} width={100} />
  <FlexGridColumn header="History" binding="history" align="center" width={180} allowSorting={false} cellTemplate={historyCellTemplate} />
  <FlexGridColumn header="Change" binding="change" align="right" width={115}>
    <FlexGridCellTemplate cellType="Cell" template={changeCellTemplate} />
  </FlexGridColumn>
  <FlexGridColumn header="Rating" binding="rating" align="center" width={180} cssClass="cell-rating" cellTemplate={ratingCellTemplate} />
  <FlexGridColumn header="Time" binding="time" format="HH:mm" isRequired={false} width={95} editor={timeEditor}>
  </FlexGridColumn>
  <FlexGridColumn header="Color" binding="colorId" dataMap={colorMap} width={145}>
    <FlexGridCellTemplate cellType="Cell" template={colorCellTemplate} />
  </FlexGridColumn>
  <FlexGridColumn header="Product" binding="productId" dataMap={productMap} width={145} />
  <FlexGridColumn header="Discount" binding="discount" format="p0" width={130} />
  <FlexGridColumn header="Active" binding="active" width={100} />
</FlexGrid>
);

}


Grid/Overview

my code isnt perfect but make job done

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions