Skip to content

Instantly share code, notes, and snippets.

@zt4ff
Created August 31, 2024 01:10
Show Gist options
  • Save zt4ff/1e4f1b61eb449d5d55b59b9eae941094 to your computer and use it in GitHub Desktop.
Save zt4ff/1e4f1b61eb449d5d55b59b9eae941094 to your computer and use it in GitHub Desktop.
Rows Selection for ka-table - single selection or multi
import "ka-table/style.css";
import React, { useState } from "react";
import { ITableProps, kaReducer, Table as KaTable } from "ka-table";
import { DataType, EditingMode, SortingMode } from "ka-table/enums";
import { DispatchFunc } from "ka-table/types";
import {
selectRow,
deselectRow,
selectAllVisibleRows,
deselectAllVisibleRows,
} from "ka-table/actionCreators";
import { kaPropsUtils } from "ka-table/utils";
const dataArray = Array(10)
.fill(undefined)
.map((_, index) => ({
column1: `column:1 row:${index}`,
column2: `column:2 row:${index}`,
column3: `column:3 row:${index}`,
column4: `column:4 row:${index}`,
id: index,
}));
const tablePropsInit: ITableProps = {
columns: [
{ key: "column1", title: "Column 1", dataType: DataType.String },
{ key: "column2", title: "Column 2", dataType: DataType.String },
{ key: "column3", title: "Column 3", dataType: DataType.String },
{ key: "column4", title: "Column 4", dataType: DataType.String },
],
data: dataArray,
editingMode: EditingMode.Cell,
rowKeyField: "id",
sortingMode: SortingMode.Single,
};
const SelectionCell = ({ rowKeyValue, dispatch, isSelectedRow }) => {
return (
<input
type="checkbox"
checked={isSelectedRow}
onChange={(event) => {
if (event.currentTarget.checked) {
dispatch(selectRow(rowKeyValue));
} else {
dispatch(deselectRow(rowKeyValue));
}
}}
/>
);
};
const SelectionHeader = ({ dispatch, areAllRowsSelected }) => {
return (
<input
type="checkbox"
checked={areAllRowsSelected}
onChange={(event) => {
if (event.currentTarget.checked) {
dispatch(selectAllVisibleRows());
} else {
dispatch(deselectAllVisibleRows());
}
}}
/>
);
};
const Table: React.FC = () => {
const [tableProps, changeTableProps] = useState(tablePropsInit);
useState(() => {
// TODO - handle the updated selection here
console.log("Selected Rows: ", tableProps?.selectedRows);
}, [tableProps?.selectedRows]);
const dispatch: DispatchFunc = (action) => {
changeTableProps((prevState: ITableProps) => kaReducer(prevState, action));
};
return (
<KaTable
{...tableProps}
dispatch={dispatch}
childComponents={{
cellText: {
content: (props) => {
if (props.column.key === "selection-cell") {
return <SelectionCell {...props} />;
}
},
},
headCell: {
content: (props) => {
if (props.column.key === "selection-cell") {
return (
<SelectionHeader
{...props}
areAllRowsSelected={kaPropsUtils.areAllVisibleRowsSelected(
tableProps
)}
/>
);
}
},
},
}}
/>
);
};
export default Table;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment