react table expandable row code example

Example: react js expand table row

import React, { useState } from 'react';

interface TableDataInterface {
    id: number,
    date: string,
    total: number,
    status: string,
    name: string,
    points: number,
    percent: number
}

const ParentComponent = (): JSX.Element => {


    const data: TableDataInterface[] = [

        { id: 1, date: "2014-04-18", total: 121.0, status: "Shipped", name: "A", points: 5, percent: 50 },
        { id: 2, date: "2014-04-21", total: 121.0, status: "Not Shipped", name: "B", points: 10, percent: 60 },
        { id: 3, date: "2014-08-09", total: 121.0, status: "Not Shipped", name: "C", points: 15, percent: 70 },
        { id: 4, date: "2014-04-24", total: 121.0, status: "Shipped", name: "D", points: 20, percent: 80 },
        { id: 5, date: "2014-04-26", total: 121.0, status: "Shipped", name: "E", points: 25, percent: 90 },
    ]

    const [expandedRows, setExpandedRows] = useState<number[]>([]);

    const handleRowClick = (rowId: number) => {
        const currentExpandedRows = expandedRows;
        const isRowCurrentlyExpanded = currentExpandedRows.includes(rowId);

        const newExpandedRows = isRowCurrentlyExpanded ?
            currentExpandedRows.filter(id => id !== rowId) :
            currentExpandedRows.concat(rowId);

        setExpandedRows(newExpandedRows);
    }

    const renderItem = (item: TableDataInterface): JSX.Element[] => {
        const clickCallback = () => handleRowClick(item.id);
        const itemRows = [
            <tr onClick={clickCallback} key={"row-data-" + item.id}>
                <td>{item.date}</td>
                <td>{item.total}</td>
                <td>{item.status}</td>
            </tr>
        ];

        if (expandedRows.includes(item.id)) {
            itemRows.push(
                <tr key={"row-expanded-" + item.id}>
                    <td>{item.name}</td>
                    <td>{item.points}</td>
                    <td>{item.percent}</td>
                </tr>
            );
        }

        return itemRows;
    }


    let allItemRows: JSX.Element[] = [];

    data.forEach(item => {
        const perItemRows = renderItem(item);
        allItemRows = allItemRows.concat(perItemRows);
    });

    return (
        <table>{allItemRows}</table>
    );

}