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:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const tableStyle = {
border: "1px solid black",
borderCollapse: "collapse",
};
const tdStyle = {
border: "1px solid black",
};
const Table = ({ id, columns, data }) => (
<table style={tableStyle}>
<tbody>
<tr>
{columns.map(({ path, name }) => (
<th style={tdStyle} key={path}>{name}</th>
))}
</tr>
{data.map((rowData) => (
<tr key={rowData[id]}>
{columns.map(({ path }) => (
<td style={tdStyle} key={path}>
{rowData[path]}
</td>
))}
</tr>
))}
</tbody>
</table>
);
// Example use --------------------
const App = () => {
const columns = [
{ path: "id", name: "ID" },
{ path: "name", name: "Name" },
{ path: "age", name: "Age" },
];
const data = [
{ id: 1, name: 'Kate', age: 25, favFruit: '🍏' },
{ id: 2, name: 'Tom', age: 23, favFruit: '🍌' },
{ id: 3, name: 'Ann', age: 26, favFruit: '🍊' },
{ id: 4, name: 'Jack', age: 21, favFruit: '🍒' }
];
return (
<div>
<Table id="id" columns={columns} data={data} />
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );