How to create an Editable Table with add delete and search filter using ReactJS ?
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.
Creating 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.
- 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
Default Project Structure: It will look like the following.
Changing the Project Structure: We don’t need some files like App.css, logo.svg. Remove them and add a new file TableDemo.js where our table component will reside.
Example: Now write down the following code in the App.js and TableDemo.js files accordingly. Here, App is our default component where we have replaced the default code.
Step to Run Application: Run the application using the following command from the root directory of the project.
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
- The useState() is a hook in ReactJs 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.