What is the best way to retrieve the overall error status from the Material UI DataGrid?

I am currently utilizing the Material UI DataGrid element to display information from an EXCEL file. Each Excel document consists of numerous column titles with specific types assigned to them. As an example:

const columns = [
    {
        "field": "uwgroup",
        "headerName": "Group",
        "minWidth": 200,
        "editable": true
    },
    {
        "field": "Amazing column Name ",
        "flex": 1,
        "minWidth": 150,
        "editable": true
    },
    {
        "field": "Building TSI",
        "type": 'number',
        "flex": 1,
        "minWidth": 150,
        "editable": true
    },
    {
        "field": "dev",
        "flex": 1,
        "minWidth": 150,
        "editable": true
    }
]

The column titled Building TSI has been designated as a type number. To highlight error cells, I have integrated the class name invalid using cellClassName, like so:

classnames({
   invalid: !isPositiveNumber(params.value)
})

This implementation successfully enforces the class name and highlights any error cells. However, my current challenge involves counting the total number of error cells. This count is crucial as it dictates whether the grid values can be saved to the database, requiring there to be no errors present within any cells.

To address this issue, I have experimented with several solutions:

  1. Incorporating a state for errorCount and incrementing it each time a class is added. Nevertheless, this approach triggers multiple re-renders and surpasses the memory limit.
  2. Utilizing
    document.getElementByClassNames('invalid')
    to determine the length of error cells. However, this method only applies to the items currently rendered on the page, presenting inaccuracies in the count for larger Excel files with pagination.
  3. Exploring the use of the preProcessEditCellProps prop to indicate errors without identifying a way to retrieve the overall count of error cells. The main benefit is restricting users from entering incorrect values.
  4. Experimenting with localStorage, which yields the same limitations as solution number 2 by solely evaluating the currently displayed page's content.

If anyone has encountered a similar scenario, I would greatly appreciate any insights. Having access to the cumulative error cells count would facilitate enabling or disabling the SAVE button accordingly.

One critical aspect to consider is the substantial size of the excel files, averaging between 30-40k rows and 25-40 columns. Managing state for individual cells could lead to performance issues.

Thank you in advance!

Answer №1

Utilizing another property in columns and referencing it prior to exporting for each cell/row can be beneficial.

In this scenario, calling the eligibleForExport function with the columns definition and the actual data as arguments will return a boolean indicating the presence of errors. It can also be modified to tally the number of errors.

const isInvalidBuildingTSI = (value) => !isPositiveNumber(value);

const isPositiveNumber = (num) => num >= 0;

const eligibleForExport = (columns, data) => {
    return !(data.find(row => columns.find(column => row[column.field] 
        && typeof column["isValid"] === "function" && column["isValid"](row[column.field])))
}

const columns = [
    {
        "field": "uwgroup",
        "headerName": "Group",
        "minWidth": 200,
        "editable": true
    },
    {
        "field": "Building TSI",
        "type": 'number',
        "flex": 1,
        "minWidth": 150,
        "editable": true,
        "isValid": isInvalidBuildingTSI,
        "cellClassName": isInvalidBuildingTSI(param.value) ? "invalid" : ""
    }
];

Answer №2

In case your initial data is consistently valid, a straightforward solution to address your problem would be to refer to the DataGrid documentation regarding client-side validation:

Client-side validation 🔗

To validate the values in the cells, start by incorporating a preProcessEditCellProps callback into the column definition of the specific field needing validation. Once this function is triggered, evaluate the provided value in params.props.value. Subsequently, return a new object containing params.props along with the error attribute set as either true or false. If the error attribute is true, the value will not be committed.

const columns: GridColDef[] = [
  {
    field: 'firstName',
    preProcessEditCellProps: (params: GridEditCellPropsChangeParams) => {
      const hasError = params.props.value.length < 3;
      return { ...params.props, error: hasError };
    },
  },
];

Applying this approach to your situation would entail the following:

const columns = [
    {
        "field": "uwgroup",
        "headerName": "Group",
        "minWidth": 200,
        "editable": true
    },
    {
        "field": "Amazing column Name ",
        "flex": 1,
        "minWidth": 150,
        "editable": true
    },
    {
        "field": "Building TSI",
        "type": 'number',
        "flex": 1,
        "minWidth": 150,
        "editable": true,
        preProcessEditCellProps(params) {
            const invalid = !isPositiveNumber(params.props.value);
            return { ...params.props, error: invalid };
        }
    },
    {
        "field": "dev",
        "flex": 1,
        "minWidth": 150,
        "editable": true
    }
]

An important distinction from your current setup is highlighted here. This validation specifically applies to edits. Therefore, it is essential for the initial data to be valid. The benefit is that you no longer have to utilize

classnames({ invalid: !isPositiveNumber(params.value) })
, and the save button can remain enabled since all applied changes are presumed to be valid.

If there exists a possibility of the initial data being invalid, this may not align with the solution you seek.

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

elevate the div with a floating effect

My goal is to create a chat feature for users that will only be visible for a limited time period. I was thinking of using PHP and timestamp to achieve this functionality, but I also want to make the chat visually disappear by having the message div float ...

What is the correct method for adjusting the height properties of an element?

I'm trying to adjust the height of my div using the code below var heightMainDiv = window.innerHeight - 50; var myDiv = $("#main_content")[0]; myDiv.clientHeight = heightMainDiv; myDiv.scrollHeight = heightMainDiv; However, the values of clientHeigh ...

Bring in d3 from unpkg

Uncertain of which file to import, I am seeking guidance on how to import d3 from unpkg.com. Can someone advise me on the equivalent unpkg version of: import * as d3 from "d3"; ...

Animation that responds to scrolling movements

Is there a way to animate text based on scrolling? <p class="class">TEXT</p> transform:translateX(-500px);opacity:0; transform:translateX(0px);opacity:1; ...

Mastering the art of using either promises or callbacks properly

Attempting to retrieve the result of a variable after completing all asynchronous processes in a function. I've discovered that I need to use promises for this, so I spent today learning about them. I've implemented promises in my function and c ...

Setting up user roles using Firebase Auth in NextJS application

Seeking a solution to implement a multi-level role system for my blog website. Currently utilizing Firebase Auth for authentication with email/password, but all users have the same posting/editing access. Looking to differentiate between Admins, Moderators ...

Converting SHA-256 from Java to JavaScript in an Ionic project using NPM: A step-by-step guide

In Java, I have a code snippet that needs to be converted into JavaScript using the Ionic Framework. I attempted to use Ionic App along with NPM packages like "crypto-js" and "js-sha256", but I was unable to find a suitable solution. String generate ...

What is the best way to arrange a GeoJSON features array based on a specific property value?

I need help sorting a GeoJSON file based on a property and then slicing it to keep only the top 5 features. For instance, I want to take this GeoJSON and arrange it in descending order by the incidents property: ... [ -75.1972382872565 ...

When viewing an array, the objects' values are displayed clearly; however, when attempting to access a specific value, it

I am attempting to retrieve the board_id of my objects in the columnsServer array... columnsServer: Column[]; this.service.getColumns() .subscribe(data => { this.columnsServer = data; console.log(this.columnsServer); for (this.i = 0; this.i ...

Important notice: Warning for stand-alone React 18 page regarding the import of createRoot from "react-dom"

I am in the process of developing a standalone webpage utilizing React 18: <!DOCTYPE html> <html lang="en"> <head> <title>Hello React!</title> <script crossorigin src="https://unpkg.com/react@1 ...

Tips for organizing a list of strings into columns within a React Bootstrap Table 2 without overflowing the designated columns

While working on rendering data in tabular form using react-bootstrap-table, I encountered an issue where the data in one column was overlapping with data from other columns. In order to maintain a fixed layout, I added the CSS layout:fixed, which was a ne ...

Develop a jQuery dialog box without assigning an ID

I need help with jQuery to create a dialog that opens and then populates with values. When I tried to create the dialog using jQuery, it kept using old values because the div already existed on the page. I want to create a new instance of the dialog usin ...

Checking the Ajax request with an if statement

$("#Submit").click(function(event){ event.preventDefault(); var th = '<tr><th>' + "Business" +'</th><th>' + "Address"+ '</th><th>'+ "Rating" + '</th><th>' + "Da ...

What is the best way to pass a file and a string to my C# backend using JQuery Ajax?

I have a user interface with two input fields - one for uploading a file and another for entering the file's name. I need to capture both the file (as binary data) and its corresponding name in a single AJAX request, so that I can upload the file usi ...

Guide: How to transfer the output from MongoDB in Node.js to AngularJS?

Currently, I am using Node.js to query my data from a MongoDB database. However, I am facing an issue where the data is not being sent out as expected when running this particular function. var findIco = function(db, callback) { var cursor = db.collec ...

Tips for locating the .owl-video-frame class using jQuery in Owl Carousel 2

In my carousel, I have multiple videos displayed as follows: <div id="owl4" class="owl-carousel owl-theme"> <div class="owl-item-container video-aspect-16-9" data-aspect="1.7777778"> <a class="owl-video" href ...

Create an Interactive Menu Using JSON Data

Looking for guidance with angularjs as a beginner, I'm interested in creating a dynamic menu using JSON array. { "Pages": [{ "PageId": 1, "PageTitle": "Home", "PageContent": "Home Page Content", "MenuType": "MainMenu", "ParentMenu": null, "PageStatu ...

The Proper Way to Include External CSS in a Next.js Page Without Triggering Any Warnings

I find myself in a scenario where I must dynamically inject CSS into a webpage. The content of this page is constantly changing, and I am provided with raw HTML and a link to a CSS file from a server that needs to be displayed on the page. My attempt to ...

Is it possible to store data from a form directly into a MongoDB database?

I am looking to store data collected from an HTML form into a MongoDB database. Below is the code I am using: <!DOCTYPE html> <html> <head> <title>Getting Started with Node and MongoDB</title> </head> <body> ...

Customize specific styles for individual divs one at a time (without the use of jQuery)

Can you assist me with this issue? I am trying to display the <span class="badge badge-light"><i class="fa fa-check-circle"></i></span> tag (initially set to "visibility: hidden") when clicking on a div with the class "role-box". He ...