MUI XGrid Disabling Export button from GridToolBar

Viewed 1615

How to disable/overide Export button of XGrid's GridToolbar in MUI?

5 Answers

There is no prop for the Export button so far. But I already made a ticket for this in the material ui github, so I hope this that should be resolved soon.

You can create your own toolbar using GridToolbarContainer and items that you need. For example if you need only column and filter buttons code will look like this:

CodeSandbox example

This is how you can make your custom export button with disabled property using useGridApiRef which is available in DataGridPro:

Notice that apiRef must be passed to DataGrid as apiRef={apiRef}

https://codesandbox.io/s/mui-datagridpro-disable-export-as-csv-button-pewlff?file=/src/App.tsx:476-1339

Toolbar

import { MutableRefObject, useState } from "react";
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import { Button } from "@mui/material";
import { GridToolbarContainer } from "@mui/x-data-grid";
import { GridApiPro } from "@mui/x-data-grid-pro/models/gridApiPro";

type Props = {
  apiRef: MutableRefObject<GridApiPro>;
};

const Toolbar = ({ apiRef }: Props) => {
  const [disabled, setDisabled] = useState(true);

  const onExportClick = () =>
    apiRef.current.exportDataAsCsv({ delimiter: ";", utf8WithBom: true });

  return (
    <GridToolbarContainer>
      <Button
        startIcon={<SaveAltIcon />}
        onClick={onExportClick}
        disabled={disabled}
      >
        {apiRef.current.getLocaleText("toolbarExport")}
      </Button>
      <Button onClick={() => setDisabled((state) => !state)}>
        {disabled ? "Enable" : "Disable"} export button
      </Button>
    </GridToolbarContainer>
  );
};

export default Toolbar;

App

export default function App() {
  const apiRef = useGridApiRef();
  
  return (
    <DataGridPro
      autoHeight
      apiRef={apiRef}
      components={{
        Toolbar
      }}
      componentsProps={{ toolbar: { apiRef } }}
      rows={rows}
      columns={columns}
    />
  );
}

Here an example with only the "Columns" visibility Button, using same analogy you can build any custom ToolBar by puting only needed tools.

import {
 DataGrid,
 GridToolbarContainer
 GridToolbarColumnsButton,
 // Check available tools in the docs
} from '@mui/x-data-grid';
 // your custom ToolBar
 const CustomToolbar = () => <GridToolbarContainer>
       <GridToolbarColumnsButton>,
       // other tools here
   </GridToolbarContainer>

 // Your Grid
 <DataGrid
    // other Props here
    components={{
      Toolbar: CustomToolbar,
    }}
  //...
Related