Ask Your Question
2

How can the header label be made dynamic in react-table?

asked 2022-01-09 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-01-24 12:00:00 +0000

david gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-01-09 11:00:00 +0000

Seen: 11 times

Last updated: Jan 24 '23