EN
React - how to create dynamic table (with dynamic header)
0 points
In this article, we would like to show you how to create a dynamic table in React.
Below example uses the following concept:
- table is described by columns and data properties,
- table is composed of header and data parts,
- the column 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.
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
};
9
10
const tdStyle = {
11
border: "1px solid black",
12
};
13
14
const Table = ({ id, columns, data }) => (
15
<table style={tableStyle}>
16
<tbody>
17
<tr>
18
{columns.map(({ path, name }) => (
19
<th style={tdStyle} key={path}>{name}</th>
20
))}
21
</tr>
22
{data.map((rowData) => (
23
<tr key={rowData[id]}>
24
{columns.map(({ path }) => (
25
<td style={tdStyle} key={path}>
26
{rowData[path]}
27
</td>
28
))}
29
</tr>
30
))}
31
</tbody>
32
</table>
33
);
34
35
// Example use --------------------
36
37
const App = () => {
38
const columns = [
39
{ path: "id", name: "ID" },
40
{ path: "name", name: "Name" },
41
{ path: "age", name: "Age" },
42
];
43
44
const data = [
45
{ id: 1, name: 'Kate', age: 25, favFruit: '🍏' },
46
{ id: 2, name: 'Tom', age: 23, favFruit: '🍌' },
47
{ id: 3, name: 'Ann', age: 26, favFruit: '🍊' },
48
{ id: 4, name: 'Jack', age: 21, favFruit: '🍒' }
49
];
50
51
return (
52
<div>
53
<Table id="id" columns={columns} data={data} />
54
</div>
55
);
56
};
57
58
const root = document.querySelector('#root');
59
ReactDOM.render(<App />, root );