I need to select the first row of the DataTable on page load and select other row(single row) on keyboard arrow keys clicked. I'm trying to achieve row selection using onKeyDown prop and here is my code
import React, { useState, useEffect, useRef } from "react";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
const ReactDataTable = ({ columnDefs, rowData, ...rest }) => {
const [selectedRow, setSelectedRow] = useState(null);
const newRowData = rowData?.map((each, index) => ({
...each,
slectedRowIndex: index,
}));
const onRowSelect = (event) => {
setSelectedRow(event.data);
};
const dataTableRef = useRef(null);
useEffect(() => {
if (dataTableRef.current) {
if (newRowData?.length > 0) {
setSelectedRow(newRowData[0]);
}
}
}, [rowData]);
const onKeyDown = (e) => {
if (e.key === "ArrowUp" || e.key === "ArrowDown") {
e.preventDefault();
const selectedIndex = selectedRow
? newRowData.findIndex(
(item) => item.slectedRowIndex === selectedRow.slectedRowIndex
)
: -1;
let newIndex = selectedIndex;
if (e.key === "ArrowUp") {
newIndex = selectedIndex > 0 ? selectedIndex - 1 : 0;
} else if (e.key === "ArrowDown") {
newIndex =
selectedIndex < newRowData.length - 1
? selectedIndex + 1
: selectedIndex;
}
setSelectedRow(newRowData[newIndex]);
}
};
return (
<div className="card react-data-table">
<DataTable
ref={dataTableRef}
onRowSelect={onRowSelect}
selectionMode="single"
selection={selectedRow}
onSelectionChange={(e) => setSelectedRow(e.value)}
onKeyDown={(e) => onKeyDown(e)}
value={newRowData}
scrollable
scrollHeight="400px"
tableStyle={{ minWidth: "50rem" }}
resizableColumns
showGridlines
columnResizeMode="expand"
{...rest}
>
{columnDefs.map((col, i) => (
<Column
key={col.field}
field={col.field}
header={col.headerName}
style={{ width: "20%" }}
/>
))}
</DataTable>
</div>
);
};
export default ReactDataTable;
The first element on page load is selected but it is not selecting the other rows when arrow keys are clicked. How can I achieve that functionality. It's only working if we click on any of the row in DataTable. Can you help me where I'm doing wrong.
Prime react DataTable, Selecting first row on page load and select(on row) other row on arrow keyboard keys clicked.
-
- Information
-
Who is online
Users browsing this forum: No registered users and 1 guest