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

Tips on redirecting the treeview menu using Material-UI 4

Currently, I am utilizing Material UI 4's Treeview component. However, I am struggling to figure out how to include a parameter that allows me to redirect to other pages when the user clicks on an item. In the past, I relied on a different method. Ch ...

What could be causing my handle button to slide off the timeline towards the right?

I'm facing an issue with my volume bar component where the slider button is rendering outside of the timeline instead of on top of the progress bar. I need assistance in adjusting its position. // Here is the code for my volume bar component: import ...

Here's a unique version: "Strategies for effectively closing a modal when moving to a

I'm currently working with react-router-dom and material UI modal, and I am looking for a way to automatically hide the modal whenever the user navigates to another page. Here is my App component: const App = () => ( <BrowserRouter> &l ...

Different ways to verify if a Checkbox is selected within a table

As a newcomer to reactjs, I have a component that renders two tables with different data using the same component and passing data through props. Each table has checkboxes for selection. If a user selects items from both tables, I want to detect if they ha ...

What is the best way to remove text from a box when a user clicks on it?

After successfully placing G in the selected box upon clicking it, I now want to work on removing it when clicked again. I'm encountering an issue with my current code - can anyone help me identify what's wrong and suggest a solution? Below is ...

Stylis-plugin-rtl for Material-UI V5 ensures that your application is fully compatible

I am using Material UI 5 with Next.js and have followed all the steps outlined in the documentation here, along with the Emotion and Stylis-plugin-rtl v2: https://next.material-ui.com/guides/right-to-left/#heading-jss However, after refreshing the page, ...

"Pushing elements into an array does not function properly within a promise

I'm having trouble with my code - the push method isn't working and it's not returning anything. import {nearbyUsers, getLatitude, getLongitude} from './helper' const users = [] nearbyUsers(session, getLatitude(), getLongitude()).t ...

Is there a way to refresh the animation on dougtesting.net?

I'm working with the dougtesting.net library to create a spinning wheel. I've been trying to figure out how to reset the animation once it finishes, but I can't seem to find any information on it. My goal is to completely clear all states so ...

Getting dynamic props from a clicked element in React involves accessing the target element's properties and

I am currently working with a React "tree" menu component that has main links with submenus generated dynamically through a JSON GET call. Upon inspecting the tree in the React Inspector, I noticed that each element has multiple props associated with it. H ...

"Unlock the Power of Reactjs Material: Simplifying the Process of Passing Props to Reactjs Material Dialog

Is there a way to pass props to a material dialog in ReactJS? When I try < FormDialog value={this.prop.value} />, I get an error saying Type '{ value: any; }' is not assignable to type 'IntrinsicAttributes'. How can I specify the ...

How to use a filtering select dropdown in React to easily sort and search options?

Recently, I started learning React and created a basic app that utilizes a countries API. The app is able to show all the countries and has a search input for filtering. Now, I want to enhance it by adding a select dropdown menu to filter countries by reg ...

Dynamically updating the ng-class name in AngularJS

Exploring the integration of animate.css with AngularJS. Attempting to assign a class to an element on ng-click, but facing difficulties in updating the element. Various strategies were attempted, including modifying scope values through functions, without ...

The CSS table-cell element causes adjacent table-cell content to reposition

The table inside the "center" div is causing the contents in the "left" div to be offset by a few pixels from the top (about 8 in my browser). When you add some text before the table, this offset disappears. Why is this happening? Is there a way to preven ...

Utilizing CSS Grid to create a modern layout design featuring a fullwidth header and footer,

I have a traditional website layout with a header, main content area with a sidebar, and a footer. I want the header and footer to span the entire width on wider screens, while the main content and sidebar are fixed width, surrounded by whitespace. When th ...

Attempting to minimize the repetition of code in Redux by implementing some utility functions

Is there a potential issue with the method I'm attempting in this URL: The concept involves altering only the actions file when introducing a new action. One improvement I am considering is recursively merging the status passed from the actions with ...

I'm having trouble displaying the result of my calculation in the code. Could it be because I forgot to include an output tag?

I am attempting to develop a Miles Per Gallon (MPG) calculator using Javascript. However, I'm encountering difficulties with displaying the results once the "Calculate" button is pressed. <html> <head> <title> MPG Calculator </ti ...

Modify the conditions of a CSS file in Bootstrap using JavaScript

My project requires internationalization support for right-to-left languages like Arabic and Hebrew, so I need to modify some Bootstrap classes (such as col) to float right instead of left. I am using create-react-app with babel/webpack and react-bootstra ...

Nested pages are causing jQuery plugins to malfunction

I am currently working on a website, but I am facing some issues with the product listing pages and the tips and tricks page. It appears that there is an issue with jMenu and jFlipBook plugins not functioning properly. Since I didn't develop the origi ...

Building a dropdown feature for rows in a table using ReactJS

I am utilizing a Material UI Table, and within one of the columns I have a SelectField component that displays a dropdown with a few selectable items. Here is a snippet of the code: <TableBody displayRowCheckbox={this.state.showCheckboxes} ...

Retrieving information from the backend results in an endless cycle, preventing it from loading successfully

My lack of experience with Async functions is evident in the issue I'm facing. The code to fetch templates from a back-end into React keeps repeating without properly setting the state to the data. import React, { useState} from 'react'; imp ...