Skip to content
Advertisement

REACT TABLE- Hide rows in table & reset button to display hidden rows

In my column Show there is a switch button (Toggle doesn’t seems working in sandbox, maybe because of tailwindcss? but it works in local…) when you click on it, it will turn the selected row into gray (as if the row is disabled but you can still view the content). We may have also the possibility to switch again and the original row (without gray) appears.

The VisibilityIcon button above the table will remove from all the table the gray/disabled rows (not working either). And a VisibilityoffIcon button that resets all (we get the original table).

Here what I have done but when I click on the Toggle I get errors and all the table is hidden:

export default function MenuDisplay() {
    const { menuId } = useParams();
    const { match } = JsonRules;
    const dataFindings = match.find((el) => el._id_menu === menuId)?._ids ?? [];
    const [disabled, setDisabled] = useState(false);

  const toggler_disabled = () => {
    disabled ? setDisabled(false) : setDisabled(true);
  };


    const data = useMemo(
        () => [
            //some headers ....    
            {
                Header: 'Show',
                accessor: (row) =>  
                  <Toggle  onClick ={toggler_disabled} value={disabled} onChange= 
                 {setDisabled} />
            }
        ],[]
    );
    ...
    return (
        {
            disabled?
                <Table 
                    data = { dataFindings }
                    columns = { data }
                />
            : null
        }
    );
}

Advertisement

Answer

  1. Keep a map of item ids that are selected and toggle these values via the Toggle component.
  2. Use separate state for the toggle button to filter the selected items.
  3. Implement a row props getter.

Example:

MenuDisplay

function MenuDisplay() {
  const { menuId } = useParams();
  const { match } = JsonData;

  // toggle show/hide button
  const [hideSelected, setHideSelected] = useState(false);

  // select rows by item id
  const [selected, setSelected] = useState({});

  const rowSelectHandler = (id) => (checked) => {
    setSelected((selected) => ({
      ...selected,
      [id]: checked
    }));
  };

  const toggleShow = () => setHideSelected((hide) => !hide);

  const matchData = (
    match.find((el) => el._id_menu === menuId)?._ids ?? []
  ).filter(({ _id }) => {
    if (hideSelected) {
      return !selected[_id];
    }
    return true;
  });

  const getRowProps = (row) => {
    return {
      style: {
        backgroundColor: selected[row.values.id] ? "lightgrey" : "white"
      }
    };
  };

  const data = [
    {
      // add item id to row data
      Header: "id",
      accessor: (row) => row._id
    },
    {
      Header: "Name",
      accessor: (row) => (
        <Link to={{ pathname: `/menu/${menuId}/${row._id}` }}>{row.name}</Link>
      )
    },
    {
      Header: "Description",
      accessor: (row) => row.description
    },
    {
      Header: "Dishes",
      accessor: (row) => row.dishes,
      id: "dishes",
      Cell: ({ value }) => value && Object.values(value[0]).join(", ")
    },
    {
      Header: "Show",
      accessor: (row) => (
        <Toggle
          value={selected[row._id]}
          onChange={rowSelectHandler(row._id)}
        />
      )
    }
  ];

  const initialState = {
    sortBy: [
      { desc: false, id: "id" },
      { desc: false, id: "description" }
    ],
    hiddenColumns: ["dishes", "id"] // <-- hide id column too
  };

  return (
    <div>
      <button type="button" onClick={toggleShow}>
        {hideSelected ? <VisibilityOffIcon /> : <VisibilityIcon />}
      </button>

      <Table
        data={matchData}
        columns={data}
        initialState={initialState}
        withCellBorder
        withRowBorder
        withSorting
        withPagination
        rowProps={getRowProps} // <-- pass rowProps getter
      />
    </div>
  );
}

Table

export default function Table({
  className,
  data,
  columns,
  initialState,
  withCellBorder,
  withRowBorder,
  withSorting,
  withPagination,
  withColumnSelect,
  rowProps = () => ({}) // <-- destructure row props getter
}) {
  ...

  return (
    <div className={className}>
      ...
      <div className="....">
        <table className="w-full" {...getTableProps()}>
          <thead className="....">
            ...
          </thead>
          <tbody {...getTableBodyProps()}>
            {(withPagination ? page : rows).map((row) => {
              prepareRow(row);
              return (
                <tr
                  className={....}
                  {...row.getRowProps(rowProps(row))} // <-- call row props getter
                >
                  ...
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Edit react-table-hide-rows-in-table-reset-button-to-display-hidden-rows

enter image description here enter image description here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement