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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-01-09 11:00:00 +0000
Seen: 11 times
Last updated: Jan 24 '23
How can I utilize a view above and between bottom tabs in React Native Navigation?
How to retrieve header and body data in Next.js using prefetch function?
How do I add a search bar to the header of my Square Space 7.1 website?
How can I use Office Script to delete all rows in Excel except for the first header row?