react js expand table row

Solutions on MaxInterview for react js expand table row by the best coders in the world

showing results for - "react js expand table row"
Sana
06 Jan 2021
1import React, { useState } from 'react';
2
3interface TableDataInterface {
4    id: number,
5    date: string,
6    total: number,
7    status: string,
8    name: string,
9    points: number,
10    percent: number
11}
12
13const ParentComponent = (): JSX.Element => {
14
15
16    const data: TableDataInterface[] = [
17
18        { id: 1, date: "2014-04-18", total: 121.0, status: "Shipped", name: "A", points: 5, percent: 50 },
19        { id: 2, date: "2014-04-21", total: 121.0, status: "Not Shipped", name: "B", points: 10, percent: 60 },
20        { id: 3, date: "2014-08-09", total: 121.0, status: "Not Shipped", name: "C", points: 15, percent: 70 },
21        { id: 4, date: "2014-04-24", total: 121.0, status: "Shipped", name: "D", points: 20, percent: 80 },
22        { id: 5, date: "2014-04-26", total: 121.0, status: "Shipped", name: "E", points: 25, percent: 90 },
23    ]
24
25    const [expandedRows, setExpandedRows] = useState<number[]>([]);
26
27    const handleRowClick = (rowId: number) => {
28        const currentExpandedRows = expandedRows;
29        const isRowCurrentlyExpanded = currentExpandedRows.includes(rowId);
30
31        const newExpandedRows = isRowCurrentlyExpanded ?
32            currentExpandedRows.filter(id => id !== rowId) :
33            currentExpandedRows.concat(rowId);
34
35        setExpandedRows(newExpandedRows);
36    }
37
38    const renderItem = (item: TableDataInterface): JSX.Element[] => {
39        const clickCallback = () => handleRowClick(item.id);
40        const itemRows = [
41            <tr onClick={clickCallback} key={"row-data-" + item.id}>
42                <td>{item.date}</td>
43                <td>{item.total}</td>
44                <td>{item.status}</td>
45            </tr>
46        ];
47
48        if (expandedRows.includes(item.id)) {
49            itemRows.push(
50                <tr key={"row-expanded-" + item.id}>
51                    <td>{item.name}</td>
52                    <td>{item.points}</td>
53                    <td>{item.percent}</td>
54                </tr>
55            );
56        }
57
58        return itemRows;
59    }
60
61
62    let allItemRows: JSX.Element[] = [];
63
64    data.forEach(item => {
65        const perItemRows = renderItem(item);
66        allItemRows = allItemRows.concat(perItemRows);
67    });
68
69    return (
70        <table>{allItemRows}</table>
71    );
72
73}