I’m using prime react table to render dynamic data in react. i build my component with the help of the datatable docs:
When I click the add row button, I would like that the new added row to be instantly editable to the user (preferably with keyboard focus that I’ll add later) without them using the edit button to edit the empty new row. Is that possible?
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
import { data2 } from "../data2";
import { useState } from "react";
import { InputText } from "primereact/inputtext";
export const Table = () => {
const [guestList, setGuestList] = useState(data2);
const handleAddRow = (): void => {
const newGuest: any = {
firstName: "",
lastName: "",
email: "",
phone: "",
freeTextField: "",
};
setGuestList((prevGuestList: any) => [newGuest, ...prevGuestList]);
};
const onRowEditComplete = (e: any) => {
const _guests = [...guestList];
const { newData, index } = e;
_guests[index] = newData;
setGuestList(_guests);
};
const textEditor = (options: any) => {
return (
<InputText
type="text"
value={options.value}
onChange={(e) => options.editorCallback(e.target.value)}
/>
);
};
return (
<div className="table-wrapper">
<h2 className="table-name">PrimeReact data table</h2>
<button onClick={handleAddRow}>add row</button>
<DataTable
value={guestList}
tableStyle={{ minWidth: "50rem" }}
editMode="row"
onRowEditComplete={onRowEditComplete}
>
<Column
field="firstName"
header="firstName"
editor={(options) => textEditor(options)}
></Column>
<Column
field="lastName"
header="lastName"
editor={(options) => textEditor(options)}
></Column>
<Column
field="email"
header="email"
editor={(options) => textEditor(options)}
></Column>
<Column
field="phone"
header="phone"
editor={(options) => textEditor(options)}
></Column>
<Column style={{ maxWidth: "15%" }} rowEditor>
edit
</Column>
</DataTable>
</div>
);
};