EN
How to create customized dynamic table in React (with dynamic header)
3 points
Hello again! π π
In the comment section under my previous post there was quite a discussion about creating a more dynamic solution for dynamic tables in React, so here we are! π
Today I wanna show you a more dynamic solution than the previous one. π₯
Effect of this short post:

In below example I used the following concept:
- table is described by columns and data properties,
- table is composed of header and some data records,
- the
columns
array allows us to decide which column names we want to display in the data rows, - using
map()
function we are able to reduce the amount of code β columns and data arrays are mapped into React components.
Note:
Remember that each element should have a unique
key
- it helps React optimally manage changes in the DOM. Such a key may be for example thepath
assigned to each element of the table.
Practical example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
β
5
const tableStyle = {
6
border: '1px solid black',
7
borderCollapse: 'collapse',
8
textAlign: 'center',
9
width: '100%'
10
}
11
β
12
const tdStyle = {
13
border: '1px solid #85C1E9',
14
background: 'white',
15
padding: '5px'
16
};
17
β
18
const thStyle = {
19
border: '1px solid #3498DB',
20
background: '#3498DB',
21
color: 'white',
22
padding: '5px'
23
};
24
β
25
const Table = ({ id, columns, data }) => (
26
<table style={tableStyle}>
27
<tbody>
28
<tr>
29
{columns.map(({ path, name }) => (
30
<th style={thStyle} key={path}>{name}</th>
31
))}
32
</tr>
33
{data.map((rowData) => (
34
<tr key={rowData[id]}>
35
{columns.map(({ path }) => (
36
<td style={tdStyle} key={path}>
37
{rowData[path]}
38
</td>
39
))}
40
</tr>
41
))}
42
</tbody>
43
</table>
44
);
45
β
46
// Example use --------------------
47
β
48
const App = () => {
49
const columns = [
50
{ path: "id", name: "ID" },
51
{ path: "name", name: "Name" },
52
{ path: "age", name: "Age" },
53
{ path: "favFruit", name: "Favourite Fruit" },
54
];
55
const data = [
56
{ id: 1, name: 'Kate', age: 25, favFruit: 'π' },
57
{ id: 2, name: 'Tom', age: 23, favFruit: 'π' },
58
{ id: 3, name: 'Ann', age: 26, favFruit: 'π' },
59
{ id: 4, name: 'Jack', age: 21, favFruit: 'π' }
60
];
61
return (
62
<div>
63
<Table id="id" columns={columns} data={data} />
64
</div>
65
);
66
};
67
β
68
const root = document.querySelector('#root');
69
ReactDOM.render(<App />, root );