reusable table in react js

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

showing results for - "reusable table in react js"
Aaron
18 Jan 2020
1import React from 'react';
2
3// This is the table constant/settings which needed to render table elements
4export const tableConstants = (handleEdit) => {
5  return [
6    {
7      title: 'ID',
8      render: rowData => {
9        return <span>{rowData.id}</span>;
10      },
11    },
12    {
13      title: 'Name',
14      render: rowData => {
15        return <span>{rowData.name}</span>;
16      },
17    },
18    {
19      title: 'Username',
20      render: rowData => {
21        return <span>{rowData.username}</span>;
22      },
23    },
24    {
25      title: 'Email',
26      render: rowData => {
27        return <span>{rowData.email}</span>;
28      },
29    },
30    {
31      title: 'Phone',
32      render: rowData => {
33        return <span>{rowData.phone}</span>;
34      },
35    },
36    {
37      title: 'Website',
38      render: rowData => {
39        return <span>{rowData.website}</span>;
40      },
41    },
42    {
43      title: 'Action',
44      render: rowData => {
45        return <button className='btn btn-warning' onClick={handleEdit(rowData)}>Edit</button>
46      },
47    },
48  ];
49};
50    
51const Table = ({ cols, data, bordered, hoverable, striped, isDark }) => {
52    return (
53        <div class="table-responsive">
54            <table className={`table ${bordered ? 'table-bordered' : 'table-borderless'} ${hoverable && 'table-hover'} ${striped && 'table-striped'} ${isDark && 'table-dark'}`}>
55                <thead>
56                    <tr>
57                        {cols.map((headerItem, index) => (
58                            <th key={index}>{headerItem.title}</th>
59                        ))}
60                    </tr>
61                </thead>
62                <tbody>
63                    {data.map((item, index) => (
64                        <tr key={index}>
65                            {cols.map((col, key) => (
66                                <td key={key}>{col.render(item)}</td>
67                            ))}
68                        </tr>
69                    ))}
70                </tbody>
71            </table>
72        </div>
73    )
74}
75
76
77import Table from '../components/Table'; 
78
79<Table cols={tableConstants(handleEdit)} data={data} isDark bordered striped hoverable />