MUI Data Grid Table - Swiss Army Knife of tables
P Sathya Narayan
Full Stack Developer at TCS | React, Node.js, Spring Boot, Flask, Django | Az900 | Microsoft Gold Student Ambassador ’23 | Building Scalable Solutions & Sharing Tech Insights
So, in today's blog, we'd like to know more about the MUI DataGrid table. 1st of all, let us understand what this is Dat Grid table.
Traditionally, in order to fully make a CRUD operation using the table. It is a task. Need to manage. a lot of states function, and let us say if we somehow managed the states. Implementing pagination, sorting, selection, Edit view, searching, and filtering all require more and more complex logic. Think of it as that friend who shows up with takeout when you are stressing about cooking a five-course meal. No need to reinvent the wheel—just roll with it!
Now let us understand in depth what is this Data Grid table using a Building a Full-Featured CRUD Grid in React with MUI DataGrid . We will take the standard example present in the MUI Documentation
Component Overview: The FullFeaturedCrudGrid
? Create new records
? Read existing records
? Update records (via row editing)
? Delete records
It leverages the power of the MUI DataGrid with built-in row editing capabilities, custom toolbars, and action buttons. Let’s break down its key features.
State Management with Rows and Row Modes
? rows: This is the heart of the data grid—your dataset. It’s initialized with initialRows, which is a static list of dummy data. The setRows function allows for dynamic updates, such as adding or deleting rows.
? rowModesModel: This state controls the mode of each row (view mode or edit mode). By tracking row states individually, you can have precise control over which rows are in editing mode at any time.
Adding a Record with the Edit Toolbar
Working
1. Clicking the Add Record Button:
? When the user clicks the button labeled “Add Record,” the function handleClick is triggered.
2. Generating a Unique ID:
? Inside handleClick, the first step is to generate a new unique ID using randomId(). This is important because every row in the table needs a unique identifier, or else the DataGrid will throw an error since it can’t have duplicate IDs.
3. Updating the Rows State:
? After generating the ID, a new row is added to the existing list of rows by updating the state (setRows). This new row starts with empty values (name: '', age: '', role: ''), ready to be filled in by the user. name age role can be changed accordingly based on your requirements
4. Switching to Edit Mode:
? Once the new row is added, it automatically enters edit mode. This is done by updating the rowModesModel state. In edit mode, the user can start typing in the fields right away.
? The rowModesModel controls whether a row is in edit or view mode. When a row is in edit mode, the fields become editable, allowing the user to modify the data directly in the table
Row Mode Control Functions: Edit, Save, Cancel, Delete
Edit Row
This function updates the rowModesModel to switch a row into edit mode when the user clicks “Edit.” The row is now editable.
Save Row
The handleSaveClick function takes the current row and changes its mode back to view mode after the user clicks “Save.”
Cancel Row
领英推荐
When the user cancels an edit, this function ensures that:
? Any unsaved changes are discarded (ignoreModifications: true).
? If the row was newly added but not saved, it’s deleted from the grid (because the isNew flag is true).
Delete Row
This function removes a row from the rows state when the “Delete” button is clicked, effectively deleting the record.
Processing Row Updates
This is the most important part. When we save the records it should be updating right . Yes we have seen when we save the record we convert from Edit mode to view mode .
The processRowUpdate function handles the update process when a row in the DataGrid is edited. It ensures that any changes made to a row are reflected in the grid’s state, specifically updating the rows array. It also marks a new row as no longer “new” once the update is processed.
Column Definitions and Action Buttons
This defines the structure of your DataGrid:
? Editable Columns: The columns (name, age, join date, role) are marked as editable, allowing users to modify them directly.
? Actions Column: The last column provides action buttons (Edit, Save, Cancel, Delete). The getActions function dynamically decides which buttons to show based on whether the row is in edit mode.
Here if we want we can add custom fields like Auto Incrementing Sno or any auto calculating fields . Like take input from any other colm and automaically calculate and populate its value.
Most important Part of DataGrid Table
params: This is an object containing details about the stop-edit event. One property of params is reason, which indicates why the row stopped being edited. Common reasons include:
? rowFocusOut: When the user clicked or tabbed out of the row.
? escapeKeyDown: When the user hit the Escape key to cancel editing.
? enterKeyDown: When the user pressed Enter to save changes.
event: The event parameter represents the native event triggered by the stop-edit action. It’s useful for managing specific event behaviors.
params.reason === GridRowEditStopReasons.rowFocusOut: This checks if the reason for stopping the row edit was due to the user clicking or focusing outside the row.
event.defaultMuiPrevented = true: When set to true, it tells the DataGrid to prevent its default behavior for this specific rowFocusOut stop-edit event. Here, it prevents the grid from saving or stopping editing automatically when focus moves out of the row.
slots={{
toolbar: EditToolbar,
}}
slotProps={{
toolbar: { setRows, setRowModesModel },
}}
Customization
Adding Auto Incrementing Serial Number
Here we will get all the rows's id and will find its index and then Add 1 to it . In the below dig we can see the output of params.api.getAllRowIds()
Conclusion
The MUI DataGrid is a powerful tool for building fully functional and customizable CRUD tables in React. With built-in support for row editing, custom toolbars, dynamic action buttons, and extensive event handling, it streamlines complex table interactions. From state management and process control with rowModesModel to advanced features like Filtering, Data validation, the DataGrid allows you to create efficient and user-friendly interfaces. By leveraging these capabilities, you can simplify complex logic, reduce development time, and focus on delivering a seamless user experience in your applications.