table icon indicating copy to clipboard operation
table copied to clipboard

defaultColumn is not working in class based component, using react-table with typeScript

Open lavania-aditya opened this issue 6 years ago • 2 comments

issue Problem is here: Class component Table File Attachment: classComponentTable.txt Functional component Table File Attachment: functionalComponentTable.txt

using defaultColumn props is not accepting in class-based component even after declaring the interfaces for typescript, same is working in the functional component but not in class component

(property) defaultColumn?: Partial<Column> | undefined Value of type '() => { Filter: ({ column: { filterValue, preFilteredRows, setFilter } }: HeaderProps) => Element; }' has no properties in common with type 'Partial<Column>'. Did you mean to call it?ts(2560) index.d.ts(114, 5): The expected type comes from property 'defaultColumn' which is declared here on type 'TableOptions'

Value of type '() => { Filter: ({ column: { filterValue, preFilteredRows, setFilter } }: HeaderProps) => Element; }' has no properties in common with type 'Partial<Column>'. Did you mean to call it?ts(2560) index.d.ts(114, 5): The expected type comes from property 'defaultColumn' which is declared here on type 'TableOptions'

Lines of code start here:

import` React from "react";
import {
  useTable,
  useSortBy,
  Column,
  useFilters,
  FilterProps,
  useGroupBy,
  useExpanded,
  usePagination,
  useRowSelect,
  HeaderGroup
} from "react-table";

import { Modal, Form, Button } from "react-bootstrap";

import "./tableStyle.scss";

import Header from "../layouts/Header";
import SpinnerLoader from "../layouts/Spinner";

declare module "react-table" {
  // take this file as-is, or comment out the sections that don't apply to your plugin configuration

  interface TableOptions<D extends object>
    extends UseExpandedOptions<D>,
      UseFiltersOptions<D>,
      UseGroupByOptions<D>,
      UsePaginationOptions<D>,
      UseRowSelectOptions<D>,
      UseSortByOptions<D> {}

  interface TableInstance<D extends object = {}>
    extends UseExpandedInstanceProps<D>,
      UseFiltersInstanceProps<D>,
      UseGroupByInstanceProps<D>,
      UsePaginationInstanceProps<D>,
      UseRowSelectInstanceProps<D>,
      UseSortByInstanceProps<D> {
    editable: boolean;
  }

  interface TableState<D extends object = {}>
    extends UseExpandedState<D>,
      UseFiltersState<D>,
      UseGroupByState<D>,
      UsePaginationState<D>,
      UseRowSelectState<D>,
      UseSortByState<D> {}

  interface Column<D extends object = {}>
    extends UseFiltersColumnOptions<D>,
      UseGroupByColumnOptions<D>,
      UseSortByColumnOptions<D> {}

  interface ColumnInstance<D extends object = {}>
    extends UseFiltersColumnProps<D>,
      UseGroupByColumnProps<D>,
      UseSortByColumnProps<D> {}

  interface Cell<D extends object = {}> extends UseGroupByCellProps<D> {}

  interface Row<D extends object = {}>
    extends UseExpandedRowProps<D>,
      UseGroupByRowProps<D>,
      UseRowSelectRowProps<D> {}
}

type Data = object;

type IProps = {
  columns: Column<Data>[];
  data: Data[];
};

type IState = {
  items: any;
  isLoaded: boolean;
  modalShow: boolean;
};

let rowId = "";
let modalData = {
  id: "",
  name: "",
  email: "",
  body: ""
};
class ClassComponentTable extends React.Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
      modalShow: false
    };
  }

  componentDidMount() {
    this.setState({ isLoaded: true });
    fetch("https://jsonplaceholder.typicode.com/comments")
      .then((res: any) => res.json())
      .then(result => {
        this.setState({ isLoaded: false });
        this.setState({ items: result });
      })
      .catch(error => {
        console.log(error);
      });
  }

  DefaultColumnFilter = ({
    column: { filterValue, preFilteredRows, setFilter }
  }: FilterProps<Data>) => {
    const count = preFilteredRows.length;
    return (
      <input
        value={filterValue || ""}
        onChange={e => {
          setFilter(e.target.value || undefined); // Set undefined to remove the filter entirely
        }}
        placeholder={`Search ${count} records...`}
      />
    );
  };

  handleShow = (column: any, row: any) => {
    const data = row.original;
    rowId = row.id;
    if (column.Header === "Select Row") {
      alert(
        "Selected Data for row: " +
          rowId +
          "\nId: " +
          data.id +
          "\nName: " +
          data.name +
          "\nEmail: " +
          data.email +
          "\nBody: " +
          data.body
      );
    } else {
      modalData.id = data.id;
      modalData.name = data.name;
      modalData.email = data.email;
      modalData.body = data.body;
      this.setState({ modalShow: true });
    }
  };

  handleClose = () => {
    this.setState({ modalShow: false });
  };

  handleSave = (rowId: string, modalData: any) => {
    const newrowId = parseInt(rowId);
    this.updateData(
      newrowId,
      "id",
      modalData.id,
      "name",
      modalData.name,
      "email",
      modalData.email,
      "body",
      modalData.body
    );
    this.setState({ modalShow: false });
  };

  updateData = (
    rowIndex: any,
    columnId1: any,
    value1: any,
    columnId2: any,
    value2: any,
    columnId3: any,
    value3: any,
    columnId4: any,
    value4: any
  ) => {
    // We also turn on the flag to not reset the page
    this.setState({
      items: (old: any) =>
        old.map((row: any, index: any) => {
          if (index === rowIndex) {
            return Object.assign(Object.assign({}, old[rowIndex]), {
              [columnId1]: value1,
              [columnId2]: value2,
              [columnId3]: value3,
              [columnId4]: value4
            });
          }
          return row;
        })
    });
  };

  onChange = (e: any) => {
    const target: string = e.target.name;
    const value: any = e.target.value;
    switch (target) {
      case "id":
        modalData.id = value;
        break;
      case "name":
        modalData.name = value;
        break;
      case "email":
        modalData.email = value;
        break;
      case "body":
        modalData.body = value;
        break;
      default:
    }
  };

  render() {
    const columnHeaders = [
      { Header: "Select Row", Cell: () => <input type="checkbox" /> },
      { Header: "ID", accessor: "id", filter: "fuzzyText" },
      { Header: "Name", accessor: "name", filter: "fuzzyText" },
      { Header: "Email", accessor: "email", filter: "fuzzyText" },
      { Header: "Body", accessor: "body", filter: "fuzzyText" }
    ];

    const TableStructure: React.FC<IProps> = ({ columns, data }) => {
      const filterTypes = () => ({
        text: (rows: any[], id: React.ReactText, filterValue: any) => {
          return rows.filter(row => {
            const rowValue = row.values[id];
            return rowValue !== undefined
              ? String(rowValue)
                  .toLowerCase()
                  .startsWith(String(filterValue).toLowerCase())
              : true;
          });
        }
      });

      const defaultColumn = () => ({
        // Let's set up our default Filter UI
        Filter: this.DefaultColumnFilter
      });

      // Use the state and functions returned from useTable to build your UI
      const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        prepareRow,
        page,
        canPreviousPage,
        canNextPage,
        pageOptions,
        pageCount,
        gotoPage,
        nextPage,
        previousPage,
        setPageSize,
        state: { pageIndex, pageSize }
      } = useTable<Data>(
        {
          columns,
          data,
          defaultColumn, // This line is the issue, the error typed above is showing on this line
          filterTypes,
          initialState: { pageIndex: 0 }
        },
        useFilters,
        useGroupBy,
        useSortBy,
        useExpanded,
        usePagination,
        useRowSelect // useGlobalFilter!
      );

      // Render the UI for your table
      return (
        <>
          <Modal show={this.state.modalShow} onHide={this.handleClose}>
            <Modal.Header closeButton>
              <Modal.Title>Index of the row: {parseInt(rowId)}</Modal.Title>
            </Modal.Header>
            <Modal.Body>
              <Form.Group>
                <Form.Label>User Id</Form.Label>
                <Form.Control
                  type="text"
                  name="id"
                  defaultValue={modalData.id}
                  onChange={this.onChange}
                />
              </Form.Group>
              <Form.Group>
                <Form.Label>Name</Form.Label>
                <Form.Control
                  type="text"
                  name="name"
                  defaultValue={modalData.name}
                  onChange={this.onChange}
                />
              </Form.Group>
              <Form.Group>
                <Form.Label>Email</Form.Label>
                <Form.Control
                  type="text"
                  name="email"
                  defaultValue={modalData.email}
                  onChange={this.onChange}
                />
              </Form.Group>
              <Form.Group>
                <Form.Label>Body</Form.Label>
                <Form.Control
                  type="text"
                  name="body"
                  defaultValue={modalData.body}
                  onChange={this.onChange}
                />
              </Form.Group>
            </Modal.Body>
            <Modal.Footer>
              <Button variant="danger" onClick={this.handleClose}>
                Close
              </Button>
              <Button
                variant="primary"
                onClick={() => this.handleSave(rowId, modalData)}
              >
                Save Changes
              </Button>
            </Modal.Footer>
          </Modal>
          <table {...getTableProps()}>
            <thead>
              {headerGroups.map((headerGroup: HeaderGroup<Data>) => (
                <tr {...headerGroup.getHeaderGroupProps()}>
                  {headerGroup.headers.map((column: any) => (
                    <th {...column.getHeaderProps()}>
                      <div>
                        <span {...column.getSortByToggleProps()}>
                          {column.render("Header")}
                          {/* Add a sort direction indicator */}
                          {column.isSorted
                            ? column.isSortedDesc
                              ? " 🔽"
                              : " 🔼"
                            : ""}
                        </span>
                      </div>
                      {/* Render the columns filter UI */}
                      <div>
                        {column.canFilter ? column.render("Filter") : null}
                      </div>
                    </th>
                  ))}
                </tr>
              ))}
            </thead>
            <tbody {...getTableBodyProps()}>
              {page.map((row: any) => {
                prepareRow(row);
                return (
                  <tr {...row.getRowProps()}>
                    {row.cells.map((cell: any) => {
                      return (
                        <td
                          {...cell.getCellProps()}
                          onClick={() => this.handleShow(cell.column, row)}
                        >
                          {cell.render("Cell")}
                        </td>
                      );
                    })}
                  </tr>
                );
              })}
            </tbody>
          </table>

          {/*
        Pagination can be built however you'd like.
        This is just a very basic UI implementation:
      */}
          <div className="pagination">
            <button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
              {"<<"}
            </button>{" "}
            <button onClick={previousPage} disabled={!canPreviousPage}>
              {"<"}
            </button>{" "}
            <button onClick={nextPage} disabled={!canNextPage}>
              {">"}
            </button>{" "}
            <button
              onClick={() => gotoPage(pageCount - 1)}
              disabled={!canNextPage}
            >
              {">>"}
            </button>{" "}
            <span>
              Page{" "}
              <strong>
                {pageIndex + 1} of {pageOptions.length}
              </strong>{" "}
            </span>
            <span>
              | Go to page:{" "}
              <input
                type="number"
                defaultValue={pageIndex + 1}
                onChange={e => {
                  const page = e.target.value ? Number(e.target.value) - 1 : 0;
                  gotoPage(page);
                }}
                style={{ width: "100px" }}
              />
            </span>{" "}
            <select
              value={pageSize}
              onChange={e => {
                setPageSize(Number(e.target.value));
              }}
            >
              {[10, 20, 30, 40, 50].map(pageSize => (
                <option key={pageSize} value={pageSize}>
                  Show {pageSize}
                </option>
              ))}
            </select>
          </div>
        </>
      );
    };

    function filterGreaterThan(rows: any, id: any, filterValue: any) {
      return rows.filter((row: any) => {
        const rowValue = row.values[id];
        return rowValue >= filterValue;
      });
    }
    // This is an autoRemove method on the filter function that
    // when given the new filter value and returns true, the filter
    // will be automatically removed. Normally this is just an undefined
    // check, but here, we want to remove the filter if it's not a number
    filterGreaterThan.autoRemove = (val: string) => typeof val !== "number";

    if (this.state.isLoaded === true) {
      return <SpinnerLoader />;
    } else {
      return (
        <React.Fragment>
          <Header
            message={"This is React Table Demo in Class based Component"}
          />
          <TableStructure columns={columnHeaders} data={this.state.items} />;
        </React.Fragment>
      );
    }
  }
}

export default ClassComponentTable;

lavania-aditya avatar Mar 13 '20 07:03 lavania-aditya

@tannerlinsley need guidance on this issue.

lavania-aditya avatar Mar 13 '20 11:03 lavania-aditya

This may have been fixed with the latest release. Can you upgrade and check again? If not, comment and we can reopen.

tannerlinsley avatar Apr 01 '20 22:04 tannerlinsley