Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[data grid] GridToolbarColumns button option toggling #15440

Closed
jimbo-codes opened this issue Nov 16, 2024 · 4 comments
Closed

[data grid] GridToolbarColumns button option toggling #15440

jimbo-codes opened this issue Nov 16, 2024 · 4 comments
Labels
component: data grid This is the name of the generic UI component, not the React module! feature: Column visibility support: commercial Support request from paid users support: pro standard Support request from a Pro standard plan user. https://mui.com/legal/technical-support-sla/

Comments

@jimbo-codes
Copy link

jimbo-codes commented Nov 16, 2024

The problem in depth

Hi - I believe this code was working previously but now seems to not allow me to hide specific fields in the column picker.

const hiddenFields = ['actions']; // Specify any fields you want to hide from the toggle
// Get togglable columns function
const getTogglableColumns = (columns) => {
  return columns
    .filter((column) => !hiddenFields.includes(column.field))
    .map((column) => column.field);
};
// this log correctly displays the filtered columns.
console.log(getTogglableColumns(headers));

The code inside the below return isnt visibile for some reason, here is the component im rendering
GridToolbarColumnsButton getTogglableColumns={getTogglableColumns(headers)}

return (
  <GridToolbarColumnsButton
    getTogglableColumns={getTogglableColumns(headers)}
  />
)

My column panel is not filtered as I would have thought it should be.

Your environment

`npx @mui/envinfo`
  Don't forget to mention which browser you used.
  Output from `npx @mui/envinfo` goes here.
❯ npx @mui/envinfo Need to install the following packages: @mui/[email protected] Ok to proceed? (y) y

System:
OS: macOS 14.5
Binaries:
Node: 22.2.0 - ~/.config/nvm/versions/node/v22.2.0/bin/node
npm: 10.7.0 - ~/.config/nvm/versions/node/v22.2.0/bin/npm
pnpm: Not Found
Browsers:
Chrome: 130.0.6723.117
Edge: Not Found
Safari: 17.5
npmPackages:
@emotion/react: ^11.13.3 => 11.13.3
@emotion/styled: ^11.13.0 => 11.13.0
@mui/base: 5.0.0-beta.40
@mui/core-downloads-tracker: 5.16.7
@mui/icons-material: ^5.15.18 => 5.16.7
@mui/lab: ^5.0.0-alpha.170 => 5.0.0-alpha.173
@mui/material: ^5.16.7 => 5.16.7
@mui/private-theming: 6.1.4
@mui/styled-engine: 6.1.4
@mui/system: ^6.1.0 => 6.1.4
@mui/types: 7.2.18
@mui/utils: 5.16.6
@mui/x-data-grid: ^7.18.0 => 7.21.0
@mui/x-data-grid-generator: ^7.16.0 => 7.21.0
@mui/x-data-grid-premium: 7.21.0
@mui/x-data-grid-pro: ^7.18.0 => 7.21.0
@mui/x-date-pickers: ^7.16.0 => 7.21.0
@mui/x-internals: 7.21.0
@mui/x-license: 7.21.0
@types/react: 18.3.11
react: ^18.2.0 => 18.3.1
react-dom: ^18.2.0 => 18.3.1
typescript: 4.9.5

(.venv)

Search keywords: Grid toolbar column visibility toggling
Order ID: 99081

@jimbo-codes jimbo-codes added status: waiting for maintainer These issues haven't been looked at yet by a maintainer support: commercial Support request from paid users labels Nov 16, 2024
@github-actions github-actions bot added component: data grid This is the name of the generic UI component, not the React module! support: pro standard Support request from a Pro standard plan user. https://mui.com/legal/technical-support-sla/ labels Nov 16, 2024
@michelengelen michelengelen changed the title GridToolbarColumns button option toggling [data grid] GridToolbarColumns button option toggling Nov 18, 2024
@michelengelen
Copy link
Member

Hey @jimbo-codes ... the way you pass the function is incorrect. getTogglableColumns accepts a function and you are calling the function and just pass the returned value.

Also you could simplify it a bit, since you only want to filter for the 'actions' column:

// Get togglable columns function
const getTogglableColumns = (columns) => {
  return columns
    .filter((column) => column.field !== 'actions')
    .map((column) => column.field);
};

You then use this function as a value to pass it to the props:

return (
  <GridToolbarColumnsButton
    getTogglableColumns={getTogglableColumns}
  />
)

@michelengelen michelengelen added status: waiting for author Issue with insufficient information feature: Column visibility and removed status: waiting for maintainer These issues haven't been looked at yet by a maintainer labels Nov 18, 2024
@jimbo-codes
Copy link
Author

jimbo-codes commented Nov 18, 2024

Thanks for getting back to me; however, I updated how I'm passing this to reflect what you noted. The actions column still shows up in the column selection panel. This is being rendered in a custom toolbar component within my datagrid, in case that is somehow the issue. Here's some additional code for context:

        <DataGridPro
            {...mergedProps}
            className="data-grid-transition"
            sx={dataGridStyles}
            pinnedRows={pinnedRows}
            apiRef={apiRef}
            columnVisibilityModel={memoizedColumnVisibilityModel}
            onColumnVisibilityModelChange={handleColumnVisibilityChange}
            getRowClassName={getRowClassName}
            getCellClassName={getCellClassName}
            processRowUpdate={(updatedRow, originalRow) => handleProcessRowUpdate(updatedRow, originalRow)}
            onProcessRowUpdateError={handleProcessRowUpdateError}
            slots={{
                toolbar: () => (
                    <MemoizedToolbar
                    props={props}
                    />
                ),
            }}

And the above component's code:

const MemoizedToolbar = React.memo(({props
  }) => {
    const hiddenFields = ['actions']; // Specify any fields you want to hide from the toggle
  const getTogglableColumns = (columns) => {
    console.log(columns);
    return columns
      .filter((column) => column.field !== 'actions')
      .map((column) => column.field);
  };
  
    return (
      <div>
        <div className='flex items-center justify-between'>
            <div className='flex items-center'>
              <div className='toolbar-buttons'>
                <GridToolbarColumnsButton
                  getTogglableColumns={getTogglableColumns}
                />

@github-actions github-actions bot added status: waiting for maintainer These issues haven't been looked at yet by a maintainer and removed status: waiting for author Issue with insufficient information labels Nov 18, 2024
@michelengelen
Copy link
Member

Setting getTogglableColumns on the GridToolbarColumnsButton component is incorrect.
It needs to go into the slotProps.columnsManagement property of the Datagrid.
Also using props={props} is incorrect usage of the props pattern in React.

Here is a working example:

import * as React from 'react';
import {
  DataGridPremium,
  GridToolbar,
  GridColDef,
  useGridApiRef,
  GridActionsCellItem,
} from '@mui/x-data-grid-premium';
import { randomUserName } from '@mui/x-data-grid-generator';
import { InfoOutlined } from '@mui/icons-material';

const hiddenFields = ['actions'];

const getTogglableColumns = (columns: GridColDef[]) => {
  return columns
    .filter((column) => !hiddenFields.includes(column.field))
    .map((column) => column.field);
};

const rows = [
  { id: 1, name: randomUserName() },
  { id: 2, name: randomUserName() },
  { id: 3, name: randomUserName() },
];
const columns: GridColDef[] = [
  { field: 'name', type: 'string' },
  {
    field: 'actions',
    type: 'actions',
    width: 80,
    getActions: () => [
      <GridActionsCellItem
        showInMenu={false}
        icon={<InfoOutlined />}
        label="Action"
        onClick={() => console.log('action click')}
      />,
    ],
  },
];

export default function ColumnSelectorGridCustomizeColumns() {
  const apiRef = useGridApiRef();

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGridPremium
        apiRef={apiRef}
        columns={columns}
        rows={rows}
        slots={{
          toolbar: GridToolbar,
        }}
        slotProps={{
          columnsManagement: {
            getTogglableColumns,
          },
        }}
      />
    </div>
  );
}

Next time provide a stripped down code example running in a codesandbox or on stackblitz.

For your convenience, our documentation offers templates and guides on creating targeted examples: Support - Bug reproduction

Just a friendly reminder: clean, functional code with minimal dependencies is most helpful. Complex code can make it tougher to pinpoint the exact issue. Sometimes, simply going through the process of creating a minimal reproduction can even clarify the problem itself!

Thanks for your understanding! 🙇🏼

@michelengelen michelengelen removed the status: waiting for maintainer These issues haven't been looked at yet by a maintainer label Nov 19, 2024
Copy link

This issue has been closed. If you have a similar problem but not exactly the same, please open a new issue.
Now, if you have additional information related to this issue or things that could help future readers, feel free to leave a comment.

Note

@jimbo-codes How did we do? Your experience with our support team matters to us. If you have a moment, please share your thoughts in this short Support Satisfaction survey.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: data grid This is the name of the generic UI component, not the React module! feature: Column visibility support: commercial Support request from paid users support: pro standard Support request from a Pro standard plan user. https://mui.com/legal/technical-support-sla/
Projects
None yet
Development

No branches or pull requests

2 participants