How can I stop re-rendering TanStack React Table till the input field is fully entered?

64 Views Asked by At

I am creating a table in which the unit price can be entered in one column and another column calculates the total price based on the input entered and the value from another column "Quantity" (total price = qty * unit price). I implemented this in normal table in react without any libraries but I wanted to implement filtering and sorting so I decided to migrate it to TanStack Table.

The issue is the input element gets unselected as soon as I enter even one character in the input. I found the reason might be that the table gets re-rendered as soon as I enter even one character so I cannot enter the entire input. How to fix this issue?

const defaultColumns = [

    // Accessor Column
    columnHelper.accessor("totalQty", {
      cell: (info) => info.getValue(),
      footer: (props) => props.column.id,
      header: () => <span>Quantity</span>,
    }),
    // ...other columns
    // Accessor Column
    columnHelper.accessor("unitPrice", {
      header: "Unit Price",
      footer: (props) => props.column.id,
      cell: (props) => (
        <input
          type="number"
          className="number-input"
          value={props.row.original.unitPrice}
          onChange={(e) => {
            handleUnitPriceChange(props.row.index, Number(e.target.value));
          }}
        />
      ),
    }),
    // Accessor Column
    columnHelper.accessor(
      (row) => {
        return row.totalQty ? row.totalQty * row.unitPrice : null;
      },
      {
        header: "Total Price",
        footer: (props) => props.column.id,
        cell: (props) => (
          <span>
            {props.row.original.totalQty
              ? props.row.original.totalQty * props.row.original.unitPrice
              : null}
          </span>
        ),
      }
    ),
  ];
  const table = useReactTable({
    data,
    columns: defaultColumns,
    getCoreRowModel: getCoreRowModel(),
  });

This is the function that updates unit price in the itemList:

function handleUnitPriceChange(index: number, up: number | null) {
    const updatedPurchaseReq = { ...purchaseReq };
    if (up !== null) {
      updatedPurchaseReq.itemList[index].unitPrice = up;
      updatedPurchaseReq.itemList[index].totalCost =
        up * updatedPurchaseReq.itemList[index].totalQty;
    } else {
      updatedPurchaseReq.itemList[index].unitPrice = 0;
      updatedPurchaseReq.itemList[index].totalCost = 0;
    }
    setPurchaseReq(updatedPurchaseReq);
  }

How to fix the input being unselected after each character entered?

I have tried to fix re-rendering using useMemo but it did not work. The table re-renders as soon as a character is entered.

0

There are 0 best solutions below