MUI Data Grid Table - Swiss Army Knife of tables

MUI Data Grid Table - Swiss Army Knife of tables

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!



Some of the features I can list

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

TypeScript version but you can remove the types for JS

? 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

TypeScript version but you can remove the types for JS

  • This is used for Adding new record in the Data Grid Table. We will pass this to the DataGrid Component .
  • It Switches the new row into edit mode using rowModesModel, allowing the user to immediately input data.

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

TypeScript version but you can remove the types for JS

This function updates the rowModesModel to switch a row into edit mode when the user clicks “Edit.” The row is now editable.


Save Row

TypeScript version but you can remove the types for JS

The handleSaveClick function takes the current row and changes its mode back to view mode after the user clicks “Save.”


Cancel Row

TypeScript version but you can remove the types for JS

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

TypeScript version but you can remove the types for JS

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.

  • processRowUpdate is a function that receives a newRow object, which contains the updated data for a specific row in the grid.
  • The goal of this function is to update the rows state with the modified data from the newRow.

  • Here, we are creating a new object updatedRow that copies all the properties from the newRow using the spread operator ({ ...newRow }).
  • The key change made is setting the isNew property to false. This is important because when a row is first added to the grid, it might be marked as “new” (with isNew: true). After the row has been updated, we no longer want it to be considered new, so this flag is turned off.
  • The setRows function updates the current state of rows with the latest values.
  • The key operation here is the map function, which iterates over each row in the rows array.
  • For each row, it checks if the id of the row matches the id of newRow (i.e., the row being updated).
  • If the IDs match, it replaces that row with the updatedRow (the newly updated version of the row).
  • If the IDs don’t match, the row remains unchanged.
  • Finally, the processRowUpdate function returns the updatedRow object. This is useful for the DataGrid to acknowledge the updated data and continue with its internal processes (like re-rendering or triggering other events).
  • Additionally if you want to perform vaidation like if age<18 show some pop up you can do that here

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

  • We can say this as the heart of the datagrid table . The place where we call our table .The below code


  • rows is an array where each item represents a row, typically structured as objects where keys are column IDs and values are cell data for that row.
  • columns array configures the layout of the grid’s columns. Each object in columns specifies properties like the column’s header label, field (to map with row data), width, alignment, and custom rendering logic, if needed.
  • editMode prop determines how the grid should handle editing. Setting editMode to “row” allows for row-level editing, so when a user enters edit mode, they can modify all cells in a particular row simultaneously.
  • onRowModesModelChange is triggered whenever the rowModesModel changes. handleRowModesModelChange allows you to customize how rows enter or exit edit mode, letting you capture the row state changes for further logic, such as validation or conditional editing.
  • onRowEditStop event fires when a user stops editing a row. The handleRowEditStop function allows you to manage what happens at the end of editing, such as saving changes, reverting to view mode, or handling any unsaved data.


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.

  • The above DataGrid component will not give you the Add Record Option. Inorder to to get that you need to pass

slots={{
          toolbar: EditToolbar,
        }}
slotProps={{
          toolbar: { setRows, setRowModesModel },
 }}        

Customization

Adding Auto Incrementing Serial Number

  • Doing this is quiet simple just add the following in the columns variable

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()

  • You can Add a lot of features like validation . Let us try an example . I want to give a validation if age is less than 18 one alert


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.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了