EN
How to create customized dynamic table in React
6 points
Hi everyone! 👋 😊
Last week I had a problem with creating a dynamic table in React, so I thought that maybe someone will find this solution helpful.
Effect of this short post:

I took several steps in the solution below:
- I created a dynamic table based on array,
- Each table consists of a header and some data records,
- The header is fixed and keeps the same amount of columns,
- While creating records I used
map()
function to convert array items into React elements.
Remember that each element should have a unique key 🗝️ because it helps React optimally manage changes in the DOM. Such a key may be for example the
id
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
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 App = () => {
26
const students = [
27
{ id: 1, name: 'Tom', age: 25, favFruit: '🍏' },
28
{ id: 2, name: 'Adam', age: 43, favFruit: '🍌' },
29
{ id: 3, name: 'Mark', age: 16, favFruit: '🍊' },
30
{ id: 4, name: 'John', age: 29, favFruit: '🍒' }
31
];
32
return (
33
<div>
34
<table style={tableStyle}>
35
<tbody>
36
<tr>
37
<th style={thStyle}>Id</th>
38
<th style={thStyle}>Name</th>
39
<th style={thStyle}>Age</th>
40
<th style={thStyle}>Favourite Fruit</th>
41
</tr>
42
{students.map(({ id, name, age, favFruit }) => (
43
<tr key={id}>
44
<td style={tdStyle}>{id}</td>
45
<td style={tdStyle}>{name}</td>
46
<td style={tdStyle}>{age}</td>
47
<td style={tdStyle}>{favFruit}</td>
48
</tr>
49
))}
50
</tbody>
51
</table>
52
</div>
53
);
54
};
55
56
const root = document.querySelector('#root');
57
ReactDOM.render(<App />, root );
Note:
Check out this article if you want to read more about dynamic tables. 😊