EN
React - how to create dynamic header for the table
0 points
In this article, we would like to show you how to create a dynamic header for the table in React.
To create a dynamic header we use two methods:
Object.keys()
that takes the first object from the passed array and creates table (headers
) filled with the object's properties,map()
method that renders<th>
element for each element inheaders
table.
Note:
Remember that each element should have a unique key - it helps React optimally manage changes in the DOM. In below example we create
counter
to assign keys.
Runnable 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 Header = ({ array }) => {
26
let counter = 0;
27
const headers = Object.keys(array[0] ?? {});
28
return headers.map((x) => {
29
++counter;
30
return (
31
<th style={thStyle} key={counter}>
32
{x}
33
</th>
34
);
35
});
36
};
37
38
const App = () => {
39
const students = [
40
{ id: 1, name: "Kate", age: 25, favFruit: "🍏" },
41
{ id: 2, name: "Tom", age: 23, favFruit: "🍌" },
42
{ id: 3, name: "Ann", age: 26, favFruit: "🍊" },
43
{ id: 4, name: "Jack", age: 21, favFruit: "🍒" },
44
];
45
46
return (
47
<div>
48
<table style={tableStyle}>
49
<tbody>
50
<tr>
51
<Header array={students} />
52
</tr>
53
{/* --- example data records --- */}
54
{students.map(({ id, name, age, favFruit }) => (
55
<tr key={id}>
56
<td style={tdStyle}>{id}</td>
57
<td style={tdStyle}>{name}</td>
58
<td style={tdStyle}>{age}</td>
59
<td style={tdStyle}>{favFruit}</td>
60
</tr>
61
))}
62
</tbody>
63
</table>
64
</div>
65
);
66
};
67
68
const root = document.querySelector('#root');
69
ReactDOM.render(<App/>, root );