Integrating Column Visibility with Filter and Sort Features
Demonstrate how to synchronize column visibility settings with sorting and filtering functionalities to maintain a consistent and user-friendly table interface.
const [visibleColumns, setVisibleColumns] = React.useState(['id', 'name', 'email']); // Initialize visible columns
This state maintains the IDs of visible columns. Initially, 'id', 'name', and 'email' columns are visible.
const toggleColumnVisibility = columnId => { setVisibleColumns(currentVisibleColumns => currentVisibleColumns.includes(columnId) ? currentVisibleColumns.filter(id => id !== columnId) : [...currentVisibleColumns, columnId]); };
This function toggles the visibility of a column. If the column is currently visible, it gets hidden, and vice versa.
const columns = React.useMemo(() => [ { Header: 'ID', accessor: 'id', isVisible: visibleColumns.includes('id') }, { Header: 'Name', accessor: 'name', isVisible: visibleColumns.includes('name') }, { Header: 'Email', accessor: 'email', isVisible: visibleColumns.includes('email') } ], [visibleColumns]);
Define columns for the table. The 'isVisible' property is dynamically set based on the 'visibleColumns' state, thus integrating visibility with the table's column definitions.
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow, setGlobalFilter } = useTable({ columns, data }, useFilters, useGlobalFilter, useSortBy);
Initialize the useTable hook from React Table, incorporating sorting and filtering hooks (useFilters, useGlobalFilter, useSortBy) along with the dynamic columns configuration.
const handleFilterChange = event => { setGlobalFilter(event.target.value || undefined); };
Defines a function to handle global filter changes. It updates the table's global filter state based on the user's input.