Programming & Development / April 18, 2025

Build a Dynamic React Table with Add/Delete & API Save Functionality

React dynamic table CRUD Axios API integration editable table

Looking to create a mini front-end interface that feels like a database table β€” editable rows, inline form fields, with save capability to your backend? This tutorial will guide you through building that with React and Axios. Let’s get started!

πŸ”§ Step 1: Create the React App

If you haven't already, initialize a new project using Create React App:

bash

npx create-react-app react-database-table
cd react-database-table

πŸ“¦ Step 2: Install Axios for API Requests

bash

npm install axios

πŸ“„ Step 3: Create the Table Component

Create a new file: src/TableComponent.js

jsx

import React, { useState, useEffect } from "react";
import axios from "axios";

const TableComponent = () => {
  const [rows, setRows] = useState([]);
  const [newRow, setNewRow] = useState({ college: "", department: "", isKnownAsFaculties: false });

  // Fetch data from API on component mount
  useEffect(() => {
    axios.get("/api/college-departments")
      .then(response => setRows(response.data))
      .catch(error => console.error("Error fetching data: ", error));
  }, []);

  // Handle input change for existing rows
  const handleInputChange = (e, index) => {
    const { name, value, type, checked } = e.target;
    const updatedRows = [...rows];
    updatedRows[index][name] = type === "checkbox" ? checked : value;
    setRows(updatedRows);
  };

  // Handle new row input
  const handleNewRowChange = (e) => {
    const { name, value, type, checked } = e.target;
    setNewRow(prev => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value
    }));
  };

  // Add new row to the table
  const addRow = () => {
    setRows([...rows, newRow]);
    setNewRow({ college: "", department: "", isKnownAsFaculties: false });
  };

  // Delete a specific row
  const deleteRow = (index) => {
    const updated = rows.filter((_, i) => i !== index);
    setRows(updated);
  };

  // Save all rows via API
  const saveData = () => {
    axios.post("/api/college-departments/bulk", rows)
      .then(() => alert("Data saved successfully!"))
      .catch(error => console.error("Error saving data: ", error));
  };

  return (
    <div style={{ padding: "1rem" }}>
      <table border="1" cellPadding="8" style={{ width: "100%", borderCollapse: "collapse" }}>
        <thead>
          <tr>
            <th>College</th>
            <th>Department</th>
            <th>Known As Faculties</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((row, idx) => (
            <tr key={idx}>
              <td>
                <input type="text" name="college" value={row.college} onChange={(e) => handleInputChange(e, idx)} />
              </td>
              <td>
                <input type="text" name="department" value={row.department} onChange={(e) => handleInputChange(e, idx)} />
              </td>
              <td style={{ textAlign: "center" }}>
                <input type="checkbox" name="isKnownAsFaculties" checked={row.isKnownAsFaculties} onChange={(e) => handleInputChange(e, idx)} />
              </td>
              <td>
                <button onClick={() => deleteRow(idx)}>Delete</button>
              </td>
            </tr>
          ))}
          <tr>
            <td>
              <input type="text" name="college" value={newRow.college} onChange={handleNewRowChange} placeholder="New College" />
            </td>
            <td>
              <input type="text" name="department" value={newRow.department} onChange={handleNewRowChange} placeholder="New Department" />
            </td>
            <td style={{ textAlign: "center" }}>
              <input type="checkbox" name="isKnownAsFaculties" checked={newRow.isKnownAsFaculties} onChange={handleNewRowChange} />
            </td>
            <td>
              <button onClick={addRow}>Add</button>
            </td>
          </tr>
        </tbody>
      </table>
      <button onClick={saveData} style={{ marginTop: "1rem" }}>Save Data</button>
    </div>
  );
};

export default TableComponent;

🧩 Step 4: Use the Component in App.js

Replace contents of src/App.js with:

jsx

import React from "react";
import "./App.css";
import TableComponent from "./TableComponent";

function App() {
  return (
    <div className="App">
      <h1>πŸ“š College Departments Manager</h1>
      <TableComponent />
    </div>
  );
}

export default App;

πŸ”™ Step 5: Backend API Assumptions

Assume your backend exposes these endpoints:

  • GET /api/college-departments β€” returns list of existing data
  • POST /api/college-departments/bulk β€” accepts updated list to save

You can mock this with tools like json-server, Express.js, Spring Boot, or any backend of your choice.

βœ… Features Covered

βœ… Display table rows

βœ… Add a new row

βœ… Edit inline

βœ… Delete any row

βœ… Save changes via API

🧠 Bonus Tips

  • Add form validation before adding/saving rows.
  • Implement toasts or snackbars for better UX feedback.
  • Add loading states for API requests.
  • Style with Tailwind or Material UI for a polished look.

🏁 Final Words

This app gives you a light version of a spreadsheet-style editor built in React β€” perfect for admin tools, form-based dashboards, and internal data managers. Hook it to any backend and you’re set!

Want a version with:

  • Sorting or filtering?
  • Pagination?
  • TypeScript support?



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex