Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-table hide custom accessor but include in global filtering

I am using react-table, and have a custom cell that loops through an array of associated records called 'skus'

I want to hide this column, but include it so that it can be used in the search bar for global filtering. I've been able to get the data rendered in the column, and include it in the global search filters. Now, I can't get the column hidden.

Here is 1 columns that does work with being hidden, and the column that I'm looping through that is not hiding:

   {
     Header: 'Category',
     accessor: 'brand.category.name',
     isVisible: false,
   },
   {
     Header: 'SKU',
     accessor: row => row.skus.map((sku) => `sku${sku.sku}`),
     isVisible: false,
   },

I'm using this effect to remove columns with isVisible: false, which works for

React.useEffect(() => {
  setHiddenColumns(
    columns.filter(column => (column.isVisible === false)).map(column => column.accessor)
  );
}, [setHiddenColumns, columns]);

The problem is clearly that I'm mapping through the array for the accessor, but I can't figure out how to include this in the global filter, AND hide the column.

like image 928
gwalshington Avatar asked Sep 13 '26 16:09

gwalshington


1 Answers

I am not sure what the structure of SKU is, but a few things to note:

The SKU column uses a function for its accessor. According to the documentation, if you have a function as an accessor then the ID field is required. https://react-table.tanstack.com/docs/api/useTable#column-options

Once you have an ID set for the column, you can also hide the column by passing in the ID to the initial state of the table. Let's assume you set the column ID to "SKU":

{
  id: 'SKU'
  Header: 'SKU',
  accessor: row => row.skus.map((sku) => `sku${sku.sku}`),
},

In your table instance, you can pass the initial state for hidden columns, like so:

const {
  ...
} = useTable(
{
  columns,
  data,
  initialState: {
    hiddenColumns: ['SKU']
  }
},
useGlobalFilter
);

The hiddenColumns property takes an array of string IDs for columns you want to hide.

Here's a codesandbox using examples from the react-table documentation. I modified the firstName column to use a function accessor instead of a string accessor for the purpose of demonstrating the ID field. https://codesandbox.io/s/stupefied-ardinghelli-89j20?file=/src/App.js

In the codesandbox you can unhide the firstName column, find a value to search for, rehide the firstName column and then try searching. It will still search on that column :)

like image 54
jpotts17 Avatar answered Sep 16 '26 05:09

jpotts17