Navigate back to the homepage

React @mui/x-data-grid search example

Infinitbility
React
May 14th, 2022 · 1 min read
keep affilitate

Hi Friends 👋,

Welcome To Infinitbility! ❤️

Today, we will learn to use x-data-grid Table, we will implement search functionality, and also encounter some issues like duplicate keys, and undefined keys issues.

Let’s start the today’s tutorial React @mui/x-data-grid search example

Table Of Content

  1. Installation
  2. Implement x-data-grid table
  3. Implement search functionality
  4. Resolve undefined and duplicate keys issues in x-data-grid

Okey, now we know what we are going to do let’s start with Installation.


Installation

Install material package ( MUI )

  • For NPM developers
1npm install @mui/material @emotion/react @emotion/styled
  • For Yarn developers
1yarn add @mui/material @emotion/react @emotion/styled

Install material icon package

  • For NPM developers
1npm install @mui/icons-material
  • For Yarn developers
1yarn add @mui/icons-material

Install Data grid package

  • For NPM developers
1npm install @mui/x-data-grid
  • For Yarn developers
1yarn add @mui/x-data-grid

Implement x-data-grid table

Here, we will import the x-data-grid package, define columns, create sample data, and data grid table.

1import React, { useEffect, useState } from "react";
2import { DataGrid } from '@mui/x-data-grid';
3import Box from '@mui/material/Box';
4import IconButton from '@mui/material/IconButton';
5import TextField from '@mui/material/TextField';
6import ClearIcon from '@mui/icons-material/Clear';
7import SearchIcon from '@mui/icons-material/Search';
8
9export default function DataGridExample() {
10 const [platform, setPlatform] = useState([]);
11
12 useEffect(() => {
13 let platformList = [
14 { id: 1, name: "Infinitbility", doamin: "infinitbility.com" },
15 { id: 2, name: "aGuideHub", doamin: "aguidehub.com" },
16 { id: 3, name: "SortoutCode", doamin: "sortoutcode.com" },
17 ];
18 setPlatform(platformList);
19 }, []);
20
21 const columns = [
22 { field: 'name', headerName: 'Name', width: 300 },
23 { field: 'doamin', headerName: 'Domain', width: 300 },
24 ];
25
26 return (
27 <div>
28 <h1>Platforms</h1>
29 <div style={{ height: 400, width: '100%' }}>
30 <DataGrid
31 disableColumnMenu
32 rows={platform}
33 columns={columns}
34 pageSize={10}
35 rowsPerPageOptions={[10]}
36 />
37 </div>
38 </div >
39 );
40}

Implement search functionality

To implement search functionality, we will add a search box with a search icon, and with a cross icon to clear the search text.

let’s see how we can able do that in material icons.

1import React, { useEffect, useState } from "react";
2import { DataGrid } from '@mui/x-data-grid';
3import Box from '@mui/material/Box';
4import IconButton from '@mui/material/IconButton';
5import TextField from '@mui/material/TextField';
6import ClearIcon from '@mui/icons-material/Clear';
7import SearchIcon from '@mui/icons-material/Search';
8
9export default function DataGridExample() {
10 const [platform, setPlatform] = useState([]);
11 const [searchText, setSearchText] = useState('');
12 const [rows, setRows] = useState([]);
13
14 useEffect(() => {
15 let platformList = [
16 { id: 1, name: "Infinitbility", doamin: "infinitbility.com" },
17 { id: 2, name: "aGuideHub", doamin: "aguidehub.com" },
18 { id: 3, name: "SortoutCode", doamin: "sortoutcode.com" },
19 ];
20 setPlatform(platformList);
21 setRows(platformList);
22 }, []);
23
24 const columns = [
25 { field: 'name', headerName: 'Name', width: 300 },
26 { field: 'doamin', headerName: 'Domain', width: 300 },
27 ];
28
29 function escapeRegExp(value) {
30 return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
31 }
32
33 const requestSearch = (searchValue) => {
34 const searchRegex = new RegExp(escapeRegExp(searchValue), 'i');
35 const filteredRows = platform.filter((row) => {
36 return Object.keys(row).some((field) => {
37 return searchRegex.test(row[field].toString());
38 });
39 });
40 setRows(filteredRows);
41 };
42
43 return (
44 <div>
45 <h1>Platforms</h1>
46 <div style={{ height: 400, width: '100%' }}>
47 <Box>
48 <TextField
49 variant="standard"
50 value={searchText}
51 onChange={(e) => { setSearchText(e.target.value); requestSearch(e.target.value) }}
52 placeholder="Search..."
53 InputProps={{
54 startAdornment: <SearchIcon fontSize="small" color="action" />,
55 endAdornment: (
56 <IconButton
57 title="Clear"
58 aria-label="Clear"
59 size="small"
60 style={{ visibility: searchText ? 'visible' : 'hidden', borderRadius: "57%", paddingRight: "1px", margin: "0", fontSize: "1.25rem" }}
61 onClick={(e) => {setSearchText(''); setRows(platform)} }
62 >
63 <ClearIcon fontSize="small" color="action" />
64 </IconButton>
65 ),
66 }}
67 sx={{
68 width: { xs: 1, sm: 'auto' }, m: (theme) => theme.spacing(1, 0.5, 1.5),
69 '& .MuiSvgIcon-root': {
70 mr: 0.5,
71 },
72 '& .MuiInput-underline:before': {
73 borderBottom: 1,
74 borderColor: 'divider',
75 },
76 }}
77 />
78 </Box>
79 <DataGrid
80 disableColumnMenu
81 rows={rows}
82 columns={columns}
83 pageSize={10}
84 rowsPerPageOptions={[10]}
85 />
86 </div>
87 </div >
88 );
89}

Output

when you run the above code, you will get the output of the table with a search box. let’s see the output.

React, Material data grid table example
React, Material data grid table example

Resolve undefined and duplicate keys issues in x-data-grid

Are you getting issue-related keys in the data grid after adding search functionality?

Ans:

remove the getRowId attribute from the <DataGrid /> component and then recheck, issue should be resolved…

All the best 👍.

Follow me on Twitter

Join our email list and get notified about new content

No worries, I respect your privacy and I will never abuse your email.

Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.

melio affilitate

Looking For React Native Tutorial?

we are trying to create the best Tutorial for react native developers.

When you want a daily updates about React Native Tutorial or infinitbility update subscribe to our newsletter.

Read React Native Tutorial

Request New Tutorial or Article on mail [email protected]

Guide book

Guidebook: The Javascript Monorepo Photoshop Guide

Tutorials

Categories

More articles from Infinitbility

How to change material icon size react?

React material icon size examples with guide to change as per requirement.

May 13th, 2022 · 1 min read

How to change material icon color in react?

React material icon color examples with a guide to change as per requirement.

May 12th, 2022 · 1 min read
© 2020–2022 Infinitbility
About
Link to $https://medium.com/infinitbilityLink to $https://www.facebook.com/InfinitbilityLink to $https://github.com/infinitbilityLink to $https://twitter.com/infinitbilityLink to $https://www.buymeacoffee.com/infinitbilityLink to $mailto:[email protected]