From eb4ffb06511bf528ae1d14d7e0e8a848b5e0fe30 Mon Sep 17 00:00:00 2001 From: Aleksandr Gumroian Date: Wed, 12 Feb 2025 15:31:35 +0100 Subject: [PATCH] Refactor RichTable component to use forwardRef And useImperativeHandle for improved data handling. --- src/common/RichTable/RichTable.js | 104 ++++++++++++++++-------------- 1 file changed, 56 insertions(+), 48 deletions(-) diff --git a/src/common/RichTable/RichTable.js b/src/common/RichTable/RichTable.js index 9eac79f..ddc07e2 100644 --- a/src/common/RichTable/RichTable.js +++ b/src/common/RichTable/RichTable.js @@ -5,7 +5,12 @@ * See /LICENSE for more information. */ -import React, { useMemo, useState } from "react"; +import React, { + useMemo, + useState, + useImperativeHandle, + forwardRef, +} from "react"; import { flexRender, @@ -22,6 +27,55 @@ import RichTablePagination from "./RichTablePagination"; const fallbackData = []; +const RichTable = forwardRef( + ({ columns, data, withPagination, pageSize = 5, pageIndex = 0 }, ref) => { + const tableColumns = useMemo(() => columns, [columns]); + const [tableData, setTableData] = useState(data ?? fallbackData); + const [sorting, setSorting] = useState([]); + const [pagination, setPagination] = useState({ + pageIndex, + pageSize, + }); + + useImperativeHandle(ref, () => ({ + setTableData, + })); + + const table = useReactTable({ + data: tableData, + columns: tableColumns, + getCoreRowModel: getCoreRowModel(), + getSortedRowModel: getSortedRowModel(), + getPaginationRowModel: getPaginationRowModel(), + onPaginationChange: setPagination, + onSortingChange: setSorting, + state: { + sorting, + pagination, + }, + }); + + const paginationIsNeeded = + tableData.length > pageSize && withPagination; + + return ( +
+ + + +
+ {paginationIsNeeded && ( + + )} +
+ ); + } +); + RichTable.propTypes = { /** Columns to be displayed in the table */ columns: PropTypes.array.isRequired, @@ -35,52 +89,6 @@ RichTable.propTypes = { pageIndex: PropTypes.number, }; -function RichTable({ - columns, - data, - withPagination, - pageSize = 5, - pageIndex = 0, -}) { - const tableColumns = useMemo(() => columns, [columns]); - const [tableData] = useState(data ?? fallbackData); - const [sorting, setSorting] = useState([]); - const [pagination, setPagination] = useState({ - pageIndex, - pageSize, - }); - - const table = useReactTable({ - data: tableData, - columns: tableColumns, - getCoreRowModel: getCoreRowModel(), - getSortedRowModel: getSortedRowModel(), - getPaginationRowModel: getPaginationRowModel(), - onPaginationChange: setPagination, - onSortingChange: setSorting, - state: { - sorting, - pagination, - }, - }); - - const paginationIsNeeded = tableData.length > pageSize && withPagination; - - return ( -
- - - -
- {paginationIsNeeded && ( - - )} -
- ); -} +RichTable.displayName = "RichTable"; export default RichTable;