@kadconsulting/dry
Version:
KAD Reusable Component Library
65 lines • 3.07 kB
JavaScript
// Import dependencies
import { useFilters, // React Table: The useFilters plugin hook must be placed before the pretty much all others so just leave at the top!
useTable, useGlobalFilter, useGroupBy, useSortBy, //React Table: The useSortBy plugin hook must be placed after the useGroupBy plugin hook!
useExpanded, // React Table: The useExpanded plugin hook must be placed after the useSortBy plugin hook!
usePagination, // React Table: The usePagination plugin hook must be placed after the useGroupBy plugin hook!
useRowSelect, // React Table: The useRowSelect plugin hook must be placed after the useGroupBy plugin hook!
useResizeColumns, useBlockLayout, useFlexLayout, } from 'react-table';
import { useMemo, useCallback } from 'react';
// Helper function to merge initial state with additional state properties
function mergeInitialState(initialState, additionalState) {
return {
...initialState,
...additionalState,
};
}
// Implementing the useCustomTable function
export function useCustomTable(options) {
const initialState = useMemo(() => mergeInitialState(options.initialState || {}, {
columnOrder: [],
columnWidths: {},
filters: [],
sortBy: [],
}), [options.initialState]);
const plugins = [
useFilters, // React Table: The useFilters plugin hook must be placed before the pretty much all others so just leave at the top!
useGlobalFilter,
useGroupBy,
useSortBy, //React Table: The useSortBy plugin hook must be placed after the useGroupBy plugin hook!
useExpanded, // React Table: The useExpanded plugin hook must be placed after the useSortBy plugin hook!
usePagination, // React Table: The usePagination plugin hook must be placed after the useGroupBy plugin hook!
useRowSelect, // React Table: The useRowSelect plugin hook must be placed after the useGroupBy plugin hook!
useResizeColumns,
useBlockLayout,
useFlexLayout,
];
const instance = useTable({
...options,
initialState,
}, ...plugins);
const toggleRowExpanded = useCallback((id, isExpanded) => {
instance.state.expandedRowIds[id] = isExpanded;
instance.setGlobalFilter([]);
}, [instance.state, instance.setGlobalFilter]);
const setColumnOrder = useCallback((newOrder) => {
instance.state.columnOrder = newOrder;
}, [instance.state]);
const setColumnWidth = useCallback((id, width) => {
instance.state.columnWidths[id] = width;
}, [instance.state]);
return {
...instance,
setGlobalFilter: instance.setGlobalFilter,
setPageSize: instance.setPageSize,
gotoPage: instance.gotoPage,
nextPage: instance.nextPage,
previousPage: instance.previousPage,
setColumnOrder,
toggleRowSelected: instance.toggleRowSelected,
toggleRowExpanded,
setColumnWidth,
state: instance.state,
selectedFlatRows: instance.selectedFlatRows,
};
}
//# sourceMappingURL=useCustomTable.js.map