import React, { ReactNode, useState } from 'react'; import classNames from 'classnames'; import Accordion from '../Accordion'; import './TableWithAccordion.scss'; import Icon from '../Icon'; import NoData from '../NoData/NoData'; import Tooltip from '../Tooltip'; import '../../../index.scss'; interface ColumnProps { /** * column name */ header: string; /** * data key for particular column */ accessor: string; /** * className for a column */ className?: string; /** * width of a column */ width?: number; /** * data for the column */ cell?: (e: any) => JSX.Element | string | ReactNode; } interface DataProps { /** * data for each row */ [key: string]: any; } export interface TableProps { /** * Column details for table */ tableMeta: Array; /** * Data for table */ tableData: Array; /** * Table type */ accordionType: 'row' | 'column'; /** * Specific sentence to be displayed data not found */ noDataText?: string; /** * Size of the image that to be displayed if you don't have data */ noDataImageSize?: 'x-large' | 'large' | 'medium' | 'small' | 'x-small'; /** * Header type */ variant: 'primary' | 'secondary'; /** * withFixedHeader prop to have non-scrollable fixed accordion table header */ withFixedHeader?: boolean; /** * Height of the table in string */ height?: string; /** * Header type to have different background color */ headerType: 'default' | 'primary' | 'secondary'; } const TableWithAccordion = ({ tableMeta = [], tableData = [], accordionType = 'row', noDataText = 'No Data Found', noDataImageSize, variant = 'secondary', height = '100%', withFixedHeader = false, headerType, }: TableProps) => { const [expandedRowIndex, setExpandedRowIndex] = useState(-1); const onAccordionClick = (index: number) => { setExpandedRowIndex(index === expandedRowIndex ? -1 : index); }; const prepareCellData = (dataObj: any, columnObj: ColumnProps) => { let cellData = dataObj[columnObj.accessor]; if (columnObj.cell) { return columnObj.cell({ value: cellData, row: dataObj, column: columnObj.accessor, }); } else if (columnObj.accessor) { return cellData; } else if (cellData && typeof cellData !== 'object') { return cellData; } else { return '--'; } }; const prepareData = (dataArray: any) => { const accordionSubTable = dataArray.map((rowData: any, index: number) => { return ( {tableMeta.map((column, i) => { return ( ); })}
{accordionType === 'column' && i === 0 ? '' : prepareCellData(rowData, column)}
); }); return accordionSubTable; }; return (
{tableMeta.map((column) => ( ))}
{column.header}
{accordionType === 'row' && tableData.map((row: any, index: number) => ( ))} {accordionType === 'column' && tableData.map((row: any, index: number) => (
{row.title}
{ !row.disable && onAccordionClick(index); }} >
{expandedRowIndex === index &&
{prepareData(row.data)}
}
))} {tableData.length <= 0 && ( )}
); }; export default TableWithAccordion;