Setting filters programmatically in Mui X Data Grid

I am currently working with the MUI Data Grid (pro version) and I am looking to implement checkboxes in the sidebar to filter different columns. Consider three columns:

* Column Letters:  ['a', 'b', 'c', 'd', etc.]
* Column Numbers:  [1, 2, 3, 4,5, etc.]
* Column Names:  ['Bob', 'Bill', 'Jim', 'Joe', etc]

Now, let's say I have various checkboxes in my sidebar:

* First 10 letters of the alphabet: []
* Last 10 letters of the alphabet: []
* Even numbers: []
* Odd numbers: []
* Names that begin with 'B': []
* Names that begin with 'J': [] 

My goal is for users to select one or more checkboxes and have them filter the corresponding columns. The challenge lies in connecting these checkboxes to the Data Grid. Setting up filters for odd numbers or names starting with 'B' isn't the issue; it's how to link custom checkboxes to apply such filters.

I considered using apiRef: https://mui.com/x/react-data-grid/api-object/

In particular, utilizing setFilterModel as mentioned on the Grid Api docs: https://mui.com/x/api/data-grid/grid-api/

The approach described above doesn't seem to be working. Here's what I attempted (using a button instead of a checkbox):

import { useGridApiRef } from "@mui/x-data-grid-pro";
export default function Sidebar({) {
  const apiRef = useGridApiRef();

  <DataGridPro
    apiRef={apiRef}
    components={{ Toolbar: GridToolbar }}
    rows={rowsData}
    columns={columnsData}
  />

  <Button
    variant="contained"
    onClick={() =>
      apiRef.current.setFilterModel([
        {
          id: 1,
          columnField: "roic10y",
          operatorValue: ">=",
          value: 10,
        },
      ])
    }
  >
    Set Filter Model
  </Button>
  );
}

Upon clicking this button, an error occurs stating:

TypeError: Cannot read properties of undefined (reading 'length')

https://i.sstatic.net/KUElq.png

Am I following the correct approach? Should I be using setFilterModel? If so, where am I going wrong and how can I rectify it? If not, what alternative method should I explore?

Thanks :).

Answer №1

Encountered your question while facing a similar issue. Here is the description of GridFilterItem's structure that the function setFilterModel requires. It expects an object with at least a property named items.

import { GridFilterItem, GridLogicOperator } from './gridFilterItem';
/**
 * Model that defines the filters to be applied on the grid.
 * @demos
 *   - [Pass filters to the grid](/x/react-data-grid/filtering/#pass-filters-to-the-data-grid)
 */
export interface GridFilterModel {
    /**
     * @default []
     */
    items: GridFilterItem[];
    /**
     * - `GridLogicOperator.And`: all filter items must be passed by the row.
     * - `GridLogicOperator.Or`: at least one filter item must be passed by the row.
     * @default `GridLogicOperator.Or`
     */
    logicOperator?: GridLogicOperator;
    /**
     * values used for quick filtering rows
     * @default `[]`
     */
    quickFilterValues?: any[];
    /**
     * - `GridLogicOperator.And`: all values must be passed by the row.
     * - `GridLogicOperator.Or`: at least one value must be passed by the row.
     * @default `GridLogicOperator.And`
     */
    quickFilterLogicOperator?: GridLogicOperator;
    /**
     * If set to `true`, the quick filter will exclude cell values from hidden columns.
     * @default false
     */
    quickFilterExcludeHiddenColumns?: boolean;
}

Therefore, you can potentially set it up like this:

onClick={() =>
 apiRef.current.setFilterModel({
  items: [
   {
    id: 1,
    columnField: "roic10y",
    operatorValue: ">=",
    value: 10,
   },
  ]
 })
}

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

Create a new function within the GraphQL Resolvers file

I am trying to define a function within the same ts file as where I specify the resolvers export const resolvers = { Query: { books: () => { return [ { title: 'Harry Potter and the Chambe ...

Adjusting the range input alters color progressively

I am trying to create a range input with a dynamic background color that changes as the slider is moved. Currently, the background is blue but I want it to start as red and transition to yellow and then green as the slider moves to the right. Does anyone ...

Removing a checker piece in the game of checkers after successfully jumping over it

Recently completed a game of checkers and managed to figure out the logic for moving and jumping checker pieces. However, I'm now facing an issue with implementing the logic for removing or deleting a jumped-over checker piece. How can I automaticall ...

Issue with Firefox pageMod addon: window.location not functioning properly

I'm developing a unique Firefox Add-on that implements page redirects based on keyboard input. The keyboard detection is functioning properly, however, the redirect functionality seems to be failing. The complete code can be found on GitHub (even thou ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...

Ensuring a DIV remains fixed in place for a specific number of scrolls

I'm looking to create a 'Page section' that remains in place while scrolling for a specific distance and then smoothly transitions to the next section. I've attempted to implement this within the child theme without success... Any sugge ...

Creating a table in Javascript using an array of objects

I need a larger version of this data structure. [{ "votes":200, "invalid_votes":140, "valid_votes":60, "voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"} }, { "votes":300, "invalid_votes":40, "valid_votes":260, "voting_section":{"level":3, "zo ...

What are the placeholders for the "localIdentName" query tag in a custom CSS-loader for Webpack?

Just starting out with Webpack and experimenting with the css-loader. I came across the option to specify a localIdentName query tag on the Github page under "Local Scope". This tag allows us to define our own custom values for how classes should be named ...

Instructions for creating a dynamic Google map based on an address

Specifics I am aiming to generate a map based on any address stored within my <span> The address in question is : 410 walker street Lowell MA 01851 The <span> containing the address reads as follows: Address: <span id="address" > 410 w ...

The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string. import express from 'e ...

Library of User Interface components for React Native applications

As I embark on my journey of building my first major app using React Native, a question comes to mind. Is there a UI framework available for React Native that offers pre-styled components right out of the box? Similar to how Ionic provides a base theme a ...

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

JavaScript method that accepts two functions as arguments

What is the proper syntax for passing two or more functions to a method, like in this example setInterval("javascript function",milliseconds); is the following correct? setInterval("pushmarkers();clearOverlays();loadmarkers();",5000); ...

Adding jQuery namespace to AngularJS

I'm facing a bit of an issue here. I've implemented RequireJS to manage my modules and dependencies. To prevent cluttering the global namespace, I've set up the following configuration to avoid declaring $ or jQuery globally: require.confi ...

AngularJS: Advanced Routing for Dynamic Web Applications

Hello, I am currently exploring the possibility of implementing something similar to this code snippet using AngularJS: $routeProvider .when('/root/:controllerName/blah/:blahId/blah/:blah', { templateUrl: '/tmpl/:controllerName ...

Using jQuery to assign the value of a hidden element to data being posted

When using jQuery's post() method to call an ajax action that returns JSON data ({"Success": "true" } or {"Success": "false"}), the value of a hidden HTML element is supposed to be set to the Success value in the returned object. However, after settin ...

Unnecessary scrollbar appears in the Simple Material UI dialog demonstration

My Material UI dialog consists of a grid with a scrollbar that allows scrolling even though the content fits on the screen. <Dialog open={isOpen} onClose={() => changeIsOpen(false)}> <DialogContent> <Grid containe ...

Create PDF files on-the-fly using the html-pdf module

Recently, I've been using the npm package html-pdf for generating PDF invoices dynamically. However, I encountered a problem where instead of saving values to the PDF file, it was saving ejs code. Does anyone have any insight on why this might be happ ...

Click to expand for answers to commonly asked questions

Having trouble setting up a FAQs page on my blog and can't seem to get the code right. Check out what I'm trying to do here: http://jsfiddle.net/qwL33/ Everything seems fine but when I click on the first question, both questions open up. Can som ...

Arrange DIV elements sequentially with HTML, JQuery, and CSS

Live Demo: Live Demo HTML: <div class="target"> <img src="bg-clock.png" alt="jQuery" /> </div> <div class="target2"> <img src="bg-clock.png" alt="jQuery" /> </div> CSS: .target, .target2 { ...