Table.tsx 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import _ from 'lodash';
  2. import React, { PureComponent } from 'react';
  3. import ReactTable from 'react-table';
  4. import TableModel from 'app/core/table_model';
  5. const EMPTY_TABLE = new TableModel();
  6. // Identify columns that contain values
  7. const VALUE_REGEX = /^[Vv]alue #\d+/;
  8. interface TableProps {
  9. data: TableModel;
  10. loading: boolean;
  11. onClickCell?: (columnKey: string, rowValue: string) => void;
  12. }
  13. function prepareRows(rows, columnNames) {
  14. return rows.map(cells => _.zipObject(columnNames, cells));
  15. }
  16. export default class Table extends PureComponent<TableProps> {
  17. getCellProps = (state, rowInfo, column) => {
  18. return {
  19. onClick: () => {
  20. const columnKey = column.Header;
  21. const rowValue = rowInfo.row[columnKey];
  22. this.props.onClickCell(columnKey, rowValue);
  23. },
  24. };
  25. };
  26. render() {
  27. const { data, loading } = this.props;
  28. const tableModel = data || EMPTY_TABLE;
  29. const columnNames = tableModel.columns.map(({ text }) => text);
  30. const columns = tableModel.columns.map(({ filterable, text }) => ({
  31. Header: text,
  32. accessor: text,
  33. className: VALUE_REGEX.test(text) ? 'text-right' : '',
  34. show: text !== 'Time',
  35. Cell: row => <span className={filterable ? 'link' : ''}>{row.value}</span>,
  36. }));
  37. const noDataText = data ? 'The queries returned no data for a table.' : '';
  38. return (
  39. <ReactTable
  40. columns={columns}
  41. data={tableModel.rows}
  42. getTdProps={this.getCellProps}
  43. loading={loading}
  44. minRows={0}
  45. noDataText={noDataText}
  46. resolveData={data => prepareRows(data, columnNames)}
  47. showPagination={data}
  48. />
  49. );
  50. }
  51. }