T
TanStack•2y ago
deep-jade

Trying to access a column titles to populate a dropdown

I'm fairly new to TanStack table so please forgive me if this is a simple thing to achieve. I'm having trouble accessing a column's title to populate a dropdown menu which will toggle that columns visibility. At present I pass in the title to a DataTableColumnHeader component through the header property of my columns definitions object:
{
accessorKey: 'user_id',
header: ({ column }) => <DataTableColumnHeader column={column} title='User ID' />
},
{
accessorKey: 'user_id',
header: ({ column }) => <DataTableColumnHeader column={column} title='User ID' />
},
I then have a DataTableViewOptions component which loops over each column using the getAllColumns method and filters the columns that can be hidden. I can only seem to access the column.id property though:
{table
.getAllColumns()
.filter(column => typeof column.accessorFn !== 'undefined' && column.getCanHide())
.map(column => {
return (
<DropdownMenuCheckboxItem
key={column.id}
checked={column.getIsVisible()}
onCheckedChange={value => column.toggleVisibility(!!value)}
>
{column.id}. // HERE IS WHERE I'D LIKE TO USE THE COLUMN TITLE
</DropdownMenuCheckboxItem>
);
})}
{table
.getAllColumns()
.filter(column => typeof column.accessorFn !== 'undefined' && column.getCanHide())
.map(column => {
return (
<DropdownMenuCheckboxItem
key={column.id}
checked={column.getIsVisible()}
onCheckedChange={value => column.toggleVisibility(!!value)}
>
{column.id}. // HERE IS WHERE I'D LIKE TO USE THE COLUMN TITLE
</DropdownMenuCheckboxItem>
);
})}
I understand I may need to do some refactoring here but is there a way to do this? Thanks 🙂
3 Replies
extended-salmon
extended-salmon•2y ago
ColumnDef | TanStack Table Docs
Column definitions are plain objects with the following options: Options
GitHub
nv-rental-clone/src/components/ui/data-table.tsx at 6879d23f35bf7b7...
Navotar with Tailwind and the Tanstack. Contribute to SeanCassiere/nv-rental-clone development by creating an account on GitHub.
GitHub
nv-rental-clone/src/tanstack-table.d.ts at 6879d23f35bf7b7a16429ff4...
Navotar with Tailwind and the Tanstack. Contribute to SeanCassiere/nv-rental-clone development by creating an account on GitHub.
foreign-sapphire
foreign-sapphire•2y ago
You can also combine the .filter and the consequent .map into a single reduce, to improve performance
deep-jade
deep-jadeOP•2y ago
Thanks both I’ll give this a try 😃 Thanks, this worked perfectly 🙂

Did you find this page helpful?