How to create an Editable Table with add delete and search filter using ReactJS ?
Last Updated :
19 Sep, 2024
Tables are used to display a set of data. In some projects, you need to implement the dynamic table with editable/non-editable modes where a user can add or delete any row. Also, Material UI for React has a customizable Table Component available, and it is very easy to integrate, but there is no such functionality to handle rows addition and deletion individually. We will use React.js and Material UI and implement these functionalities in it.
Approach
To create an Editable table in react with add, delete, and search filters we will manage row data using useState, implement form inputs for editing, handle add/remove operations with buttons, and use controlled components for real-time editing, deletion, and filtering.
Prerequisites
Steps to Create React Application And Installing Module
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the React.js application, install the material-ui modules using the following command.
npm install @material-ui/core @material-ui/icons
Project Structure:
Changing the Project StructureThe updated dependencies in the package.json file are:
"dependencies": {
"@material-ui/core": "^4.12.4",
"@material-ui/icons": "^4.11.3",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Example: Now write down the following code in the App.js and TableDemo.js files accordingly.
JavaScript
// Filename - App.js
import React from "react";
import TableDemo from "./TableDemo";
function App() {
return (
<div>
{/* Header with inline css */}
<h1
style={{
display: 'flex', justifyContent: 'center', padding: '15px',
border: '13px solid #b4f0b4', color: 'rgb(11, 167, 11)'
}}>
Geeks For Geeks Material UI Table
</h1>
{/* Table component below header */}
<TableDemo />
</div>
)
}
export default App;
JavaScript
// Filename - TableDemo.js
import React, { useState } from "react";
import CreateIcon from "@material-ui/icons/Create";
import {
Box, Button, Snackbar, Table,
TableBody, TableCell, TableHead, TableRow
} from "@material-ui/core";
import DeleteOutlineIcon from "@material-ui/icons/DeleteOutline";
import AddBoxIcon from "@material-ui/icons/AddBox";
import DoneIcon from "@material-ui/icons/Done";
import ClearIcon from "@material-ui/icons/Clear";
import { makeStyles } from "@material-ui/core/styles";
import Alert from "@material-ui/lab/Alert";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DialogTitle from "@material-ui/core/DialogTitle";
// Creating styles
const useStyles = makeStyles({
root: {
"& > *": {
borderBottom: "unset",
},
},
table: {
minWidth: 650,
},
snackbar: {
bottom: "104px",
},
});
function TableDemo() {
// Creating style object
const classes = useStyles();
// Defining a state named rows
// which we can update by calling on setRows function
const [rows, setRows] = useState([
{ id: 1, firstname: "", lastname: "", city: "" },
]);
// Initial states
const [open, setOpen] = React.useState(false);
const [isEdit, setEdit] = React.useState(false);
const [disable, setDisable] = React.useState(true);
const [showConfirm, setShowConfirm] = React.useState(false);
// Function For closing the alert snackbar
const handleClose = (event, reason) => {
if (reason === "clickaway") {
return;
}
setOpen(false);
};
// Function For adding new row object
const handleAdd = () => {
setRows([
...rows,
{
id: rows.length + 1, firstname: "",
lastname: "", city: ""
},
]);
setEdit(true);
};
// Function to handle edit
const handleEdit = (i) => {
// If edit mode is true setEdit will
// set it to false and vice versa
setEdit(!isEdit);
};
// Function to handle save
const handleSave = () => {
setEdit(!isEdit);
setRows(rows);
console.log("saved : ", rows);
setDisable(true);
setOpen(true);
};
// The handleInputChange handler can be set up to handle
// many different inputs in the form, listen for changes
// to input elements and record their values in state
const handleInputChange = (e, index) => {
setDisable(false);
const { name, value } = e.target;
const list = [...rows];
list[index][name] = value;
setRows(list);
};
// Showing delete confirmation to users
const handleConfirm = () => {
setShowConfirm(true);
};
// Handle the case of delete confirmation where
// user click yes delete a specific row of id:i
const handleRemoveClick = (i) => {
const list = [...rows];
list.splice(i, 1);
setRows(list);
setShowConfirm(false);
};
// Handle the case of delete confirmation
// where user click no
const handleNo = () => {
setShowConfirm(false);
};
return (
<TableBody>
<Snackbar
open={open}
autoHideDuration={2000}
onClose={handleClose}
className={classes.snackbar}
>
<Alert onClose={handleClose} severity="success">
Record saved successfully!
</Alert>
</Snackbar>
<Box margin={1}>
<div style={{ display: "flex", justifyContent: "space-between" }}>
<div>
{isEdit ? (
<div>
<Button onClick={handleAdd}>
<AddBoxIcon onClick={handleAdd} />
ADD
</Button>
{rows.length !== 0 && (
<div>
{disable ? (
<Button disabled align="right"
onClick={handleSave}>
<DoneIcon />
SAVE
</Button>
) : (
<Button align="right" onClick={handleSave}>
<DoneIcon />
SAVE
</Button>
)}
</div>
)}
</div>
) : (
<div>
<Button onClick={handleAdd}>
<AddBoxIcon onClick={handleAdd} />
ADD
</Button>
<Button align="right" onClick={handleEdit}>
<CreateIcon />
EDIT
</Button>
</div>
)}
</div>
</div>
<TableRow align="center"> </TableRow>
<Table
className={classes.table}
size="small"
aria-label="a dense table"
>
<TableHead>
<TableRow>
<TableCell>First Name</TableCell>
<TableCell>Last Name</TableCell>
<TableCell align="center">City</TableCell>
<TableCell align="center"> </TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, i) => {
return (
<div>
<TableRow>
{isEdit ? (
<div>
<TableCell padding="none">
<input
value={row.firstname}
name="firstname"
onChange={(e) =>
handleInputChange(e, i)}
/>
</TableCell>
<TableCell padding="none">
<input
value={row.lastname}
name="lastname"
onChange={(e) =>
handleInputChange(e, i)}
/>
</TableCell>
<TableCell padding="none">
<select
style={{ width: "100px" }}
name="city"
value={row.city}
onChange={(e) =>
handleInputChange(e, i)}
>
<option value=""></option>
<option value="Karanja">
Karanja
</option>
<option value="Hingoli">
Hingoli
</option>
<option value="Bhandara">
Bhandara
</option>
<option value="Amaravati">
Amaravati
</option>
<option value="Pulgaon">
Pulgaon
</option>
</select>
</TableCell>
</div>
) : (
<div>
<TableCell component="th" scope="row">
{row.firstname}
</TableCell>
<TableCell component="th" scope="row">
{row.lastname}
</TableCell>
<TableCell component="th"
scope="row"
align="center">
{row.city}
</TableCell>
<TableCell
component="th"
scope="row"
align="center"
></TableCell>
</div>
)}
{isEdit ? (
<Button className="mr10"
onClick={handleConfirm}>
<ClearIcon />
</Button>
) : (
<Button className="mr10"
onClick={handleConfirm}>
<DeleteOutlineIcon />
</Button>
)}
{showConfirm && (
<div>
<Dialog
open={showConfirm}
onClose={handleNo}
aria-labelledby="alert-dialog-title"
aria-describedby=
"alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">
{"Confirm Delete"}
</DialogTitle>
<DialogContent>
<DialogContentText
id="alert-dialog-description">
Are you sure to delete
</DialogContentText>
</DialogContent>
<DialogActions>
<Button
onClick={() =>
handleRemoveClick(i)}
color="primary"
autoFocus
>
Yes
</Button>
<Button
onClick={handleNo}
color="primary"
autoFocus
>
No
</Button>
</DialogActions>
</Dialog>
</div>
)}
</TableRow>
</div>
);
})}
</TableBody>
</Table>
</Box>
</TableBody>
);
}
export default TableDemo;
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/, you will see the following output.
Explanation:
- The useState() is a hook in React Js which allows a functional component to have a state. We pass the initial state in this function, and it returns us a variable and a function to update that state. Using this we can handle edit/non-edit mode and buttons to be displayed accordingly.
- Initially, the Table will be displayed in non-edit mode. After clicking EDIT, table rows will be modified in edit mode where the user can add as many rows or delete any row.
- In edit mode when the user tries to change row data, the EDIT button will be changed to SAVE. After clicking SAVE, a saving alert message will be popped up.
- When a user tries to delete a row, confirmation delete will be shown. If the user select yes, then that particular row will be deleted, and if the user selects no, the row will not be deleted.
- Observe the above output and notice the changes. You can also modify those changes according to your choice.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read