Want a form that behaves like a database table? In React, you can build a dynamic table that lets users add, update, and delete rows β just like editing records in a database.
π οΈ Step 1: Create Your React App
If you donβt already have a React app:
bash
npx create-react-app react-database-table-form
cd react-database-table-form
npm start
π§© Step 2: Build the Table Form Component
π src/TableForm.js
jsx
import React, { useState } from 'react';
const TableForm = () => {
const [rows, setRows] = useState([
{ id: 1, name: '', age: '', email: '' },
]);
const handleInputChange = (index, event) => {
const updatedRows = [...rows];
updatedRows[index][event.target.name] = event.target.value;
setRows(updatedRows);
};
const handleAddRow = () => {
const newRow = { id: rows.length + 1, name: '', age: '', email: '' };
setRows([...rows, newRow]);
};
const handleRemoveRow = (index) => {
const updatedRows = rows.filter((_, i) => i !== index);
setRows(updatedRows);
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Submitted Data:', rows);
};
return (
<form onSubmit={handleSubmit}>
<table border="1" cellPadding="8">
<thead>
<tr>
<th>ID</th><th>Name</th><th>Age</th><th>Email</th><th>Actions</th>
</tr>
</thead>
<tbody>
{rows.map((row, index) => (
<tr key={row.id}>
<td>{row.id}</td>
<td>
<input
name="name"
value={row.name}
onChange={(e) => handleInputChange(index, e)}
/>
</td>
<td>
<input
type="number"
name="age"
value={row.age}
onChange={(e) => handleInputChange(index, e)}
/>
</td>
<td>
<input
type="email"
name="email"
value={row.email}
onChange={(e) => handleInputChange(index, e)}
/>
</td>
<td>
<button type="button" onClick={() => handleRemoveRow(index)}>
β Remove
</button>
</td>
</tr>
))}
</tbody>
</table>
<div style={{ marginTop: '1rem' }}>
<button type="button" onClick={handleAddRow}>β Add Row</button>
<button type="submit">β
Submit</button>
</div>
</form>
);
};
export default TableForm;
π Step 3: Use the Component in App.js
jsx
import React from 'react';
import TableForm from './TableForm';
function App() {
return (
<div style={{ padding: '2rem' }}>
<h2>π Editable Table Form</h2>
<TableForm />
</div>
);
}
export default App;
π§ How It Works
FeatureDescriptionuseState
Manages rows as objects ({id, name, age, email}
)handleInputChange
Updates the specific row/field based on inputhandleAddRow
Adds a new row with an auto-incremented IDhandleRemoveRow
Removes a row based on indexhandleSubmit
Logs the entire table of inputs to the console
π§© Bonus Ideas
- Validation: Add input validation (e.g. required fields, email format)
- Styling: Use Tailwind, Bootstrap, or CSS modules for a professional look
- Database Sync: Use Axios or
fetch()
to POST the data to a backend - Row Editing/Locking: Add βEditβ/βSaveβ button per row for better UX