React onClick Add or Remove Table Rows Example Tutorial

Last updated on: by Digamber

In this tutorial, you will learn how to easily add a data row in a table component in React. Also, how to remove a data row from a table component in React.

We’ll use the useState hook in a function component to remove a particular table row or to add a new row to the table.

A functional component in React brings easiness to app development. It is an immaculate function that takes props and returns a React element.

In contrast, we will create a table component in React with a pure function to add and delete a row from the table through an onClick event handler with the help of a button.

The onClick event handler is ideally attached to a function; On invoking, the onClick handler commands a function to perform a certain action.

Therefore, we will create a dynamic table using the latest version of the Bootstrap library. After setting up the bootstrap in React, it gives us full access to multiple UI components.

We will use the bootstrap table component to design the table component, create a button, bind an onClick event handler, and pass a custom function to delete or insert a table row in React.

Build New Project

We assume you must have set up Node and NPM on your machine. Run the following command to create a new React project.

npx create-react-app react-blog

After the app is formed, move into the project folder.

cd react-blog

Install Bootstrap Module

Now, we are installing bootstrap module in our app. Make sure to execute the give command to add bootstrap module in React.

npm install bootstrap

Furthermore, open the App.js file and add the bootstrap.min.css in the main component.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

Create Component File

Let us checkout how to create a basic function component, make the new folder and name it components/ then create the Table.js file.

import React from 'react'
function Table() {
  return (
    <div>Form page</div>
  )
}
export default Table

Remove and Add Table Row in React

In this step, we are about to update the following code into the components/Table.js, this will complete our table component with props object.

import React, { useState } from "react";
function TableRows({ rows, tableRowRemove, onValUpdate }) {
  return rows.map((rowsData, index) => {
    const { name, email, profile } = rowsData;
    return (
      <tr key={index}>
        <td>
          <input
            type="text"
            value={name}
            onChange={(event) => onValUpdate(index, event)}
            name="name"
            className="form-control"
          />
        </td>
        <td>
          <input
            type="text"
            value={email}
            onChange={(event) => onValUpdate(index, event)}
            name="email"
            className="form-control"
          />
        </td>
        <td>
          <input
            type="text"
            value={profile}
            onChange={(event) => onValUpdate(index, event)}
            name="profile"
            className="form-control"
          />
        </td>
        <td>
          <button
            className="btn btn-dark"
            onClick={() => tableRowRemove(index)}
          >
            Delete Row
          </button>
        </td>
      </tr>
    );
  });
}
function Table() {
  const [rows, initRow] = useState([]);
  const addRowTable = () => {
    const data = {
      name: "",
      email: "",
      profile: "",
    };
    initRow([...rows, data]);
  };
  const tableRowRemove = (index) => {
    const dataRow = [...rows];
    dataRow.splice(index, 1);
    initRow(dataRow);
  };
  const onValUpdate = (i, event) => {
    const { name, value } = event.target;
    const data = [...rows];
    data[i][name] = value;
    initRow(data);
  };
  return (
    <>
      <h2 className="text-center">React JS Add / Delete Table Rows Example</h2>
      <table className="table table-striped">
        <thead>
          <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Profile</th>
            <th>
              <button className="btn btn-danger" onClick={addRowTable}>
                Insert Row
              </button>
            </th>
          </tr>
        </thead>
        <tbody>
          <TableRows
            rows={rows}
            tableRowRemove={tableRowRemove}
            onValUpdate={onValUpdate}
          />
        </tbody>
      </table>
    </>
  );
}
export default Table;

Add Component in Global Component

We are now going to complete our code guide by registering the Table component into the src/App.js file.

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import Table from "./components/Table";
function App() {
  return (
    <div>
      <Table />
    </div>
  );
}
export default App;

Show App on Browser

You have to run the provided command to show application on the browser; type the command and hit enter.

npm start

After starting the app server, you will see the following output on the browser.

React onClick Add or Remove Table Rows Example Tutorial

Conclusion

Generally, a table is used to show data collections grouped into rows. In this tutorial, we have explained how to build a dynamic table component in React, how to remove table rows using the onClick event handler, and how to add dynamically add rows to the table using react hooks.

We have done all the implementation in the function component.

Hence we covered: how to create a function, pass props to the function component, and how to get the values from the function component in React with examples.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.