Conditional Column Visibility
Implement conditional logic to manage the visibility of columns based on user roles or data characteristics, enhancing data table security and relevance.
const [userRole, setUserRole] = React.useState('admin');
Initializes state for the user's role.
const initialColumns = [
{ id: 'id', Header: 'ID', accessor: 'id' },
{ id: 'name', Header: 'Name', accessor: 'name' },
{ id: 'email', Header: 'Email', accessor: 'email', isVisible: userRole === 'admin' },
{ id: 'address', Header: 'Address', accessor: 'address', isVisible: userRole === 'user' }
];
Defines the initial columns for the table, with conditional visibility based on the user role.
const [columns, setColumns] = React.useState(initialColumns);
Initializes state for columns with the initial settings.
const toggleUserRole = () => {
setUserRole(prevRole => prevRole === 'admin' ? 'user' : 'admin');
};
Function to toggle the user role between 'admin' and 'user'.
React.useEffect(() => {
const updatedColumns = initialColumns.map(column => ({
...column,
isVisible: column.id === 'email' ? userRole === 'admin' : column.id === 'address' ? userRole === 'user' : true
}));
setColumns(updatedColumns);
}, [userRole]);
Effect hook to update column visibility when the user role changes.