Created
April 26, 2023 22:15
-
-
Save vishnuvyas/e04c467be7d8119347d2e9d361287b91 to your computer and use it in GitHub Desktop.
Verison of Editable Table in react and typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useRef } from "react"; | |
const Table = ({ columns, data }) => { | |
const [rows, setRows] = useState<{ [key: string]: any }[]>(data); | |
const [editMode, setEditMode] = useState(false); | |
const inputRef = useRef<HTMLInputElement[]>(); | |
const addRow = () => { | |
setRows([...rows, {}]); | |
}; | |
const deleteRow = (index: number) => { | |
setRows(rows.filter((row, i) => i !== index)); | |
}; | |
const handleEditModeChange = () => { | |
setEditMode(prevEditMode => !prevEditMode); | |
}; | |
const handleInputChange = (event, column) => { | |
const row = rows[event.target.closest("tr").dataset.row]; | |
row[column] = event.target.value; | |
setRows([...rows]); | |
}; | |
return ( | |
<div> | |
<table> | |
<thead> | |
<tr> | |
{columns.map((column, i) => ( | |
<th key={i}>{column}</th> | |
))} | |
</tr> | |
</thead> | |
<tbody> | |
{rows.map((row, i) => ( | |
<tr key={i} data-row={i}> | |
{columns.map((column, j) => ( | |
<td key={j}> | |
{editMode ? ( | |
<input | |
type="text" | |
value={row[column]} | |
onChange={(event) => handleInputChange(event, column)} | |
/> | |
) : ( | |
row[column] | |
)} | |
</td> | |
))} | |
<td> | |
{editMode ? ( | |
<button onClick={() => setEditMode(false)}>Cancel</button> | |
) : ( | |
<button onClick={() => deleteRow(i)}>Delete</button> | |
)} | |
</td> | |
</tr> | |
))} | |
<tr> | |
<td><button onClick={addRow}>Add Row</button></td> | |
</tr> | |
</tbody> | |
</table> | |
<button onClick={handleEditModeChange}>{editMode ? "Cancel Edit" : "Edit"}</button> | |
</div> | |
); | |
}; | |
export default Table; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment