frontend
frontend

Reputation: 23

How to show columns based on 2 selected dropdown react-table

[Link to Codesandbox of react-table][1]

By default it will show all the available columns and when selecting 2 dropdown values it should show the 2 columns for comparison. So therefore it should display it in react table. I see there is an example of ticking checkboxes to show which column will be hidden, but in my case I want other way around when I have show the 2 columns when both dropdown is selected before showing it.

import { FC, useState } from "react";
import { useTable } from "react-table";

interface Column {
  Header: string;
  accessor: string;
  id: Function | string | number;
}

interface TableProps {
  columns: Array<any>;
  data: Array<any>;
}

export const Table: FC<TableProps> = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    allColumns,
  } = useTable({
    data,
    columns,
  });
  const [valueOne, setValueOne] = useState("");
  const [valueTwo, setValueTwo] = useState("");
  const handleChangeOne = (e: any) => setValueOne(e.target.value);
  const handleChangeTwo = (e: any) => setValueTwo(e.target.value);

  return (
    <>
      <select value={valueOne} onChange={handleChangeOne}>
        {allColumns.map((column) => (
          <option value={column.id} {...column.getToggleHiddenProps()}>
            {column.id}
          </option>
        ))}
      </select>

      <select value={valueTwo} onChange={handleChangeTwo}>
        {allColumns.map((column) => (
          <option value={column.id} {...column.getToggleHiddenProps()}>
            {column.id}
          </option>
        ))}
      </select>

      <table {...getTableProps()}>
        <thead>
          {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map((column) => (
                <th {...column.getHeaderProps()}>{column.render("Header")}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {rows.map((row) => {
            prepareRow(row);

            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => (
                  <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                ))}
              </tr>
            );
          })}
        </tbody>
      </table>
    </>
  );
};

Upvotes: 0

Views: 984

Answers (1)

Wraithy
Wraithy

Reputation: 2056

I would just use somthing like headerGroup.headers.filter((i)=> i === valueOne || i === valueTwo ).map(.....

Upvotes: 1

Related Questions