Open In App

How to create an Editable Table with add delete and search filter using ReactJS ?

Improve
Improve
Like Article
Like
Save
Share
Report

Tables is 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.

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
npm install @material-ui/icons
npm install @material-ui/lab

Project Structure:

Changing the Project Structure

Example: Now write down the following code in the App.js and TableDemo.js files accordingly.

Javascript




//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




//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.

Table functionality Demo

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.


Last Updated : 08 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads