In this article, we will learn how to use the MUI DataGrid component with nested data with valueGetter in ReactJS. In MUI, valueGetter is a function that allows you to access nested attributes in an object. It’s a convenient way to get the value of a deeply nested property without having to write lengthy code. The valueGetter function is a custom function that you can define to extract nested data from the row object. It takes an object containing information about the current cell and returns the value to be displayed in that cell.
Approach: To use the DataGrid component with nested data and a valueGetter function, we can follow the below steps:
- Create a React application and install the required modules.
- Define the rows and columns props for the DataGrid component. The column prop should include the valueGetter function to extract nested data from the row object.
Creating React Application and Installing the required Modules:
Step 1: Create a React Application using the following command:
npx create-react-app folder-name
Step 2: Once the project is created move to the project folder by entering the following command in the Terminal:
cd folder-name
Step 3: Now, Install the MUI DataGrid package which is required for creating the DataGrid Component by using the following command:
npm install @mui/x-data-grid
Project Structure:
Example: In this example, we are using the valueGetter property in columns which is used to render the nested value (i.e. the city and state) in the column cell.
- App.js file
Javascript
import { DataGrid } from '@mui/x-data-grid' ; const rows = [ { id: 1, name: 'John Doe' , address: { city: 'New York' , state: 'NY' } }, { id: 2, name: 'Jane Smith' , address: { city: 'Los Angeles' , state: 'CA' } }, { id: 3, name: 'Bob Johnson' , address: { city: 'Chicago' , state: 'IL' } }, ]; const columns = [ { field: 'id' , headerName: 'ID' , width: 100 }, { field: 'name' , headerName: 'Name' , width: 150 }, { field: 'city' , headerName: 'City' , width: 150, valueGetter: (params) => params.row.address.city, }, { field: 'state' , headerName: 'State' , width: 150, valueGetter: (params) => params.row.address.state, }, ]; function App() { return ( <div style={{ height: 400, width: '100%' }}> <DataGrid rows={rows} columns={columns} /> </div> ); } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, and you can see the following output: