Reputation: 45
I'm kind of new to React and Web development in general .
I have a scenario , to create a table in react , and create a box that would enable to show/hide the columns with it , and along with it a select all checkbox that would show or hide all columns except a "NAME_ID" column .
I am able to achieve the earlier part with with useTable()
hook and column.getToggleHiddenProps()
method from destructured call of hook .
But I'm not able to achieve the second part , I do know that we have getToggleHideAllColumnsProps()
but that won't allow me to except the required NAME_ID column .
Any help or suggestions would be great !!.
Upvotes: 3
Views: 5161
Reputation: 1006
There is a way to accomplish this. I wish this was a boolean to pass to the Columns object, but we take what we can get.
I forked the original Hidden Columns sandbox as a proof of concept. The relevant portions are:
getToggleHideAllColumnsProps
props, you need to create your own onClick handler. column
exposes a toggleHidden
method which dictates the behavior when the user attempts to toggle that specific column. Somewhat frustratingly, even if you have implemented the toggleHidden
method for a column, getToggleHideAllColumnsProps
completely ignores it, and toggles its hidden status anyway.<div>
<IndeterminateCheckbox
onClick={() => allColumns.forEach(c => c.id !== "firstName" && c.toggleHidden())}
/>
Toggle All
</div>
Luckily, it is a fairly simple function -- just iterate over your columns
object and call toggleHidden
on each. I included a check against calling it on the desired column anyway, for robustness, but you technically don't need to.
toggleHidden
function for the desired column. I did it in the render method for the checkboxes, but it works just the same if you do it elsewhere. When the toggleHidden
function is defined for a column, it overrides the default behavior, as expected. So, you can just have an empty function that returns null, and this disables the ability to manually turn off that column.allColumns.map((column) => {
if (column.id === "firstName") {
column.toggleHidden = () => null;
}
return ( /* ...jsx... */ );
})
Upvotes: 2