1 | initial version |
To make the header label dynamic in react-table, you can pass the column definition object as an array of objects instead of a static object.
Each object in the array specifies a column label and a cell value accessor. You can use a variable to set the column label dynamically and pass it as a prop to the column definition object.
For example, let's say you have a state variable called "category" that you want to use as the header label for a column:
import React, { useState } from "react";
import { useTable } from "react-table";
function Table({ data }) {
const [category, setCategory] = useState("default");
const columns = [
{
Header: category,
accessor: "name",
},
{
Header: "Price",
accessor: "price",
},
];
const tableInstance = useTable({ columns, data });
// Render table
return (
<table>
<thead>
<tr>
{tableInstance.headers.map((column) => (
<th key={column.id}>{column.render("Header")}</th>
))}
</tr>
</thead>
<tbody>
{tableInstance.rows.map((row) => {
tableInstance.prepareRow(row);
return (
<tr key={row.id}>
{row.cells.map((cell) => (
<td key={cell.id}>{cell.render("Cell")}</td>
))}
</tr>
);
})}
</tbody>
</table>
);
}
export default Table;
In the example above, the column label is set to the value of the "category" state variable. When the state variable changes, the header label will update accordingly.