I want to update the toggle switches within the GridToolbarColumnsButton component from MUI's DataGrid to checkboxes

Currently, I am developing a website where one of the pages has tabular data fetched from the backend. To filter this table, I utilized Mui filters from datagrid({...data}components={{ toolbar: CustomToolbar }}). Among these filters is a GridToolbarColumnsButton filter, which can be seen in the uploaded image here. My goal is to replace the switches with checkboxes. What steps should I take to achieve this?

I attempted inspecting elements and using the following code snippet within datagrid:

componentsProps={{
    panel: {

      sx: {
        '& .MuiPopper-root': {
          // color: 'red',
          fontSize: 15,
          backgroundColor:'red'
        },
       }
     }
   }}

Unfortunately, despite trying to override with this code, I have not been successful.

Answer №1

Currently, there is no direct method to override GridToolbarColumnsButton in Data Grid version v6.13.0.

To achieve the same functionality, I utilized the api reference useGridApiContext, demonstrated below:

Output: enter image description here

(Note: Import statements have been omitted, remember to include them...) CustomPopupCheckboxes:

export default function CustomPopupCheckboxes(props) {
  const apiRef = useGridApiContext();

  const [visibleColumns, setVisibleColumns] = useState([]);
  const [columns, setColumns] = useState(apiRef.current.getVisibleColumns());

  useEffect(() => {
    setVisibleColumns(apiRef.current.getVisibleColumns());
  });

  return (
    <Menu
      id="long-menu"
      anchorEl={props.moreMenuAnchorEl}
      open={props.openColumnsMenu}
      onClose={() => props.setOpenColumnsMenu(!props.openColumnsMenu)}
    >
      {columns.map((column) => {
        let isVisible = visibleColumns.filter((x) => x.field == column.field);
        return (
          <div style={column.hideable ? {} : { display: "none" }}>
            <Checkbox
              checked={isVisible.length != 0 ? true : false}
              onChange={(e) => {
                apiRef.current.setColumnVisibility(
                  column.field,
                  e.target.checked
                );
                setVisibleColumns(apiRef.current.getVisibleColumns());
              }}
            />
            {column.headerName}
          </div>
        );
      })}
    </Menu>
  );
}

CustomToolbar:

export default function CustomToolbar(props) {
  const [openColumnsMenu, setOpenColumnsMenu] = useState(false);
  const [columnsMenuAnchorEl, setColumnsMenuAnchorEl] = useState(null);

  return (
    <GridToolbarContainer
      style={{
        display: "inline-block",
        textAlign: "right",
        marginBottom: "10px",
      }}
    >
        <CustomIconButton
          onClick={(event) => {
            setOpenColumnsMenu(!openColumnsMenu);
            setColumnsMenuAnchorEl(event.currentTarget);
          }}
        >
          <img src="./Icons/Columns.svg" />
        </CustomIconButton>
        <CustomPopupCheckboxes
          moreMenuAnchorEl={columnsMenuAnchorEl}
          openColumnsMenu={openColumnsMenu}
          setOpenColumnsMenu={(value) => setOpenColumnsMenu(value)}
        />
      </div>
    </GridToolbarContainer>
  );
}

In my particular situation, I needed to create an IconButton that triggers a popup with checkboxes upon clicking.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ReactDOM fails to display the application, even after successfully compiling

I am facing an issue where the app is not rendering despite successful compilation with yarn run. Here is the code snippet: import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import {Provider ...

The function .classList.remove() is effective when applied to one element, but fails to work on a different element

I am facing an issue where only one element is getting affected when trying to remove classes from multiple elements if certain email input requirements are met. Can someone help me understand why this is happening? Here is the code snippet: const emailI ...

What is the best way to create a stylish outward curve effect for an active sidebar item using just CSS

After spending a week learning frontend designs, I attempted to replicate a design from Dribble. However, I've been struggling with recreating the active style on the sidebar due to the outward curve. If anyone could provide guidance on achieving thi ...

``Is it possible to adjust the style of an HTML element based on the style of another element?

Within my web application, I am dynamically changing the style of an HTML element using JavaScript. Below is the code snippet: function layout() { if(document.getElementById('sh1').getAttribute('src') == "abc.png") { docum ...

Style the labels on the axis of Frappe Charts with colors (potentially utilizing the appropriate CSS selector)

Is it possible to style the x and y axis labels in a Frappe chart with different colors? https://i.stack.imgur.com/A3vUq.png While trying to identify the CSS selectors using Chrome DevTools, I found that a single text element (representing an x axis labe ...

Selenium was unable to find the p tag element on the webpage

I apologize for reaching out to you all for assistance with such a basic task, but I have tried everything in my toolkit and still can't seem to figure it out. I've experimented with partial xpath, full xpath, and various CSS selectors. I am see ...

Tips on combining react material ui Link and react router Link for seamless integration

My navigation bar has a routing issue that I'm trying to solve. Currently, the router only responds when the route is manually typed in the search bar. Clicking on the tabs does not redirect properly, except for the home button tab. import React from ...

The useParams() function will return an empty value upon the component's initial render

I'm utilizing React along with the following libraries: "babel-eslint": "10.0.3", "react": "^17.0.2", "react-dom": "^17.0.2", "react-redux": "^7.2.4", "react-router-dom": "^6.3.0", "react-scripts": "3.2.0", "redux": "^4.1.1 ...

The error message TS2322 in MUI v5 states that the property 'fullWidth' is not found in the type 'IntrinsicAttributes & { theme: Theme; } & { children?: ReactNode; }'

As a user of MUI v5, I have implemented a straightforward FormControl as seen below. It is important to note that the property fullWidth is supported according to the official documentation. import React, { PropsWithChildren } from 'react' import ...

Assigning a height of 100% to a div element results in the appearance of

In a div within the body, there are only 3 lines of text. The background color was only filling up to those 3 lines of text. To make the color fill up the entire vertical space of the browser, I adjusted the CSS height properties of html & body to be ...

Adjusting image size to accommodate responsive column cell using CSS

I've been working on optimizing my mobile website using a responsive column layout. The challenge I'm facing is getting the images within each column to stretch to 100% width while automatically adjusting their height. I experimented with settin ...

Several buttons, each requiring to show distinct text

Currently, I am attempting to enhance an existing project that was graciously created for me. I must admit, I am quite new to this, so please be patient with me! In my project, there are 9 buttons, each triggering the display of a different image upon bei ...

What could be the reason for my flex items not shrinking when the browser window size is decreased?

Here is the CSS code for the header component using flexbox: .header { display: flex; flex-direction: row; justify-content: space-between; padding: 15px 20px; background-color: #ffffff; position: sticky; top: 0; z-index: ...

Disappearing Bootstrap 3 Dropdown Issue Caused by Tab Click

There is an issue with the drop-down menu I created: When I click on tabs like ALL or FILM, it closes all elements. To reopen, I have to click again on the button PRODUCT.dropdown-toggle. The code example looks like this: var App = function () { ...

The CSS3 rotation transform will rotate by an angle of n degrees

I'm currently working on a cube-like element made up of 4 divs that I am rotating using CSS3 transforms (limited to -webkit for a Chrome extension). But there's an issue, if you visit http://jsfiddle.net/CxYTg/ and click through "one", "two", "t ...

There seems to be a compatibility problem between the NPM package Material UI Core, React-IS, and material-ui-color

Currently I am working with React version 17.0.2 and Material UI v5. However, I encountered an issue when trying to use the material-ui-color package as it is not compatible with React 18. To work around this limitation, I had to downgrade back to React 17 ...

Adding Material-UI icons dynamically in a React TypeScript project requires understanding the integration of imported icons

I have a collection of menu buttons with icons, stored in an array of objects. The icon names are saved as strings that correspond to Material UI icons: interface MenuButton { text: string, onClickFunction: Function icon: string } export defau ...

The UseEffect function is displaying an inappropriate value, however, it only occurs once

My goal is to display the state value whenever the password is changed using the useEffect hook in React. It's working fine for the password, but the issue arises when I try to change the email. The console also renders the email value, which is not i ...

Using HTML within a Material-UI Accordion component

I am attempting to display HTML content within an Accordion component. import {Accordion, AccordionDetails, AccordionSummary, Typography} from '@material-ui/core'; import { Badge } from 'reactstrap'; ... const buildAccordion = (f, i) ...

Using React Quill JS and looking to log to the console when a change handler is triggered?

As I dive into the world of web development, I am currently working on crafting a blog dashboard. For the text editor, I've opted to use React Quill. While following the documentation, I came across a tutorial that includes an 'on change' ha ...