mui / mui-x

MUI X: Build complex and data-rich applications using a growing list of advanced React components, like the Data Grid, Date and Time Pickers, Charts, and more!
https://mui.com/x/
4.08k stars 1.26k forks source link

[data grid] How to use Custom GridToolBar outside of the table? #14681

Open saeonny opened 1 day ago

saeonny commented 1 day ago

The problem in depth

Demo using this custom tool bar, is it possible to take out from the datagrid and use the feature?

i was thinking to use gridApiRef but did not worked

Your environment

`npx @mui/envinfo` ``` System: OS: Windows 11 10.0.22631 Binaries: Node: 20.11.0 - C:\Program Files\nodejs\node.EXE npm: 10.2.4 - C:\Program Files\nodejs\npm.CMD pnpm: Not Found Browsers: Chrome: Not Found Edge: Chromium (127.0.2651.74) npmPackages: @emotion/react: ^11.11.4 => 11.11.4 @emotion/styled: ^11.11.5 => 11.11.5 @mui/base: 5.0.0-beta.26 @mui/core-downloads-tracker: 5.15.21 @mui/icons-material: ^5.15.21 => 5.15.21 @mui/lab: ^5.0.0-alpha.155 => 5.0.0-alpha.155 @mui/material: ^5.15.21 => 5.15.21 @mui/private-theming: 5.15.20 @mui/styled-engine: 5.15.14 @mui/system: 5.15.20 @mui/types: 7.2.16 @mui/utils: 5.16.6 @mui/x-data-grid: 7.16.0 @mui/x-data-grid-pro: ^7.16.0 => 7.16.0 @mui/x-internals: 7.16.0 @mui/x-license: ^7.16.0 => 7.16.0 @mui/x-license-pro: ^6.10.2 => 6.10.2 @types/react: ^18.2.43 => 18.2.43 react: ^18.2.0 => 18.2.0 react-dom: ^18.2.0 => 18.2.0 typescript: ^5.3.3 => 5.3.3 ```

Search keywords: Custom GridToolBar Order ID: 83106

michelengelen commented 1 day ago

The Toolbar needs the Datagrid context, but you can provide a custom Toolbar (or any other component) and pass it the apiRef like this:

import * as React from 'react';
import { DataGridPremium, GridApi, useGridApiRef } from '@mui/x-data-grid-premium';
import { useDemoData } from '@mui/x-data-grid-generator';

const CustomComponent = ({ apiRef }: { apiRef: React.MutableRefObject<GridApi> }) => {
  const [rowCount, setRowCount] = React.useState(0);

  React.useEffect(() => {
    const handleSelectionChange = () => {
      setRowCount(apiRef.current?.getSelectedRows().size);
    };

    apiRef.current?.subscribeEvent('rowSelectionChange', handleSelectionChange);
  }, []);

  if (!apiRef.current?.instanceId?.id) {
    return null;
  }

  return <div>Selected Rows: {rowCount}</div>;
};

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

  const { data } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 10,
    maxColumns: 6,
    editable: true,
  });

  return (
    <div style={{ width: '100%' }}>
      <CustomComponent apiRef={apiRef} />
      <div style={{ height: 400 }}>
        <DataGridPremium apiRef={apiRef} {...data} />
      </div>
    </div>
  );
}