1
0
mirror of https://gitlab.nic.cz/turris/reforis/foris-js.git synced 2025-02-22 09:44:18 +01:00

Merge branch 'improve-richtable' into 'dev'

Refactor RichTable component to use forwardRef and useImperativeHandle for improved data handling

See merge request turris/reforis/foris-js!266
This commit is contained in:
Aleksandr Gumroian 2025-02-17 15:42:41 +01:00
commit 230ae8e35b

View File

@ -5,7 +5,12 @@
* See /LICENSE for more information. * See /LICENSE for more information.
*/ */
import React, { useMemo, useState } from "react"; import React, {
useMemo,
useState,
useImperativeHandle,
forwardRef,
} from "react";
import { import {
flexRender, flexRender,
@ -22,34 +27,20 @@ import RichTablePagination from "./RichTablePagination";
const fallbackData = []; const fallbackData = [];
RichTable.propTypes = { const RichTable = forwardRef(
/** Columns to be displayed in the table */ ({ columns, data, withPagination, pageSize = 5, pageIndex = 0 }, ref) => {
columns: PropTypes.array.isRequired,
/** Data to be displayed in the table */
data: PropTypes.array.isRequired,
/** Whether to display pagination */
withPagination: PropTypes.bool,
/** Number of rows per page */
pageSize: PropTypes.number,
/** Index of the current page */
pageIndex: PropTypes.number,
};
function RichTable({
columns,
data,
withPagination,
pageSize = 5,
pageIndex = 0,
}) {
const tableColumns = useMemo(() => columns, [columns]); const tableColumns = useMemo(() => columns, [columns]);
const [tableData] = useState(data ?? fallbackData); const [tableData, setTableData] = useState(data ?? fallbackData);
const [sorting, setSorting] = useState([]); const [sorting, setSorting] = useState([]);
const [pagination, setPagination] = useState({ const [pagination, setPagination] = useState({
pageIndex, pageIndex,
pageSize, pageSize,
}); });
useImperativeHandle(ref, () => ({
setTableData,
}));
const table = useReactTable({ const table = useReactTable({
data: tableData, data: tableData,
columns: tableColumns, columns: tableColumns,
@ -64,7 +55,8 @@ function RichTable({
}, },
}); });
const paginationIsNeeded = tableData.length > pageSize && withPagination; const paginationIsNeeded =
tableData.length > pageSize && withPagination;
return ( return (
<div className="table-responsive"> <div className="table-responsive">
@ -81,6 +73,22 @@ function RichTable({
)} )}
</div> </div>
); );
} }
);
RichTable.propTypes = {
/** Columns to be displayed in the table */
columns: PropTypes.array.isRequired,
/** Data to be displayed in the table */
data: PropTypes.array.isRequired,
/** Whether to display pagination */
withPagination: PropTypes.bool,
/** Number of rows per page */
pageSize: PropTypes.number,
/** Index of the current page */
pageIndex: PropTypes.number,
};
RichTable.displayName = "RichTable";
export default RichTable; export default RichTable;