Rasil
Rasil

Reputation: 86

How to handle empty cell values in @tanstack/react-table?

I am trying to find an optimal way to handle the empty cell values. I have following column definition in which all the fields are optional except the name field:

const columnHelper = createColumnHelper<{
    name: string; 
    contact_person?: string; 
    phone_no?: string
}>();

export const countryColumns = () => [
    columnHelper.display({
        header: "S.N.",
        cell: ({ row }) => row.index + 1,
    }),
    columnHelper.accessor("name", {
        header: "Name",
    }),
    columnHelper.accessor("contact_person", {
        header: "Contact Person",
    }),
    columnHelper.accessor("phone_no", {
        header: "Phone Number",
    }),
    columnHelper.display({
        id: "actions",
        header: "Actions",
        cell: ({ row }) => (
      // Buttons
    ),
  }),
];

Here, contact_person and phone_no are optional fields. So, there might be cases where the contact_person and phone_no will be empty in the table. How do I handle it?

export const countryColumns = () => [
    columnHelper.display({
        header: "S.N.",
        cell: ({ row }) => row.index + 1,
    }),
    columnHelper.accessor("name", {
        header: "Name",
    }),
    columnHelper.accessor("contact_person", {
        header: "Contact Person",
        cell: info => info.getValue() ?? "---";
    }),
    columnHelper.accessor("phone_no", {
        header: "Phone Number",
        cell: info => info.getValue() ?? "---";
    }),
    columnHelper.display({
        id: "actions",
        header: "Actions",
        cell: ({ row }) => (
          // Buttons
        ),
    }),
];

Here, I need to check the condition in every optional field. Is this what I should do or there is another workaround?

Also, in the main table component, I tried doing something like this:

{row.getVisibleCells().map(cell => {
    return (
        <Td key={cell.id} pl={6}>
            {cell.getValue() ? flexRender(
            cell.column.columnDef.cell,
            cell.getContext(),
        ) : "---"}
        </Td>
  );
})}

However, this renders "---" in S.N. and "Actions" field too which are display columns. This only seems to work on accessor columns.

Upvotes: 3

Views: 1621

Answers (1)

Michael Sp&#228;th
Michael Sp&#228;th

Reputation: 21

It took me some time because I couldn't find a solution in the TanStack table docs. In the end I used css to show a fallback. Maybe there is a more elegant solution?

The fallback '-' is only visible if the span containing the flexRender is empty.

<style>
  .content:empty + .fallback {
    display: 'inline';
  }

  .fallback {
    display: 'none';
  }
</style

{row.getVisibleCells().map((cell) => (
  <TableCell>
    <span className="content">
      {flexRender(cell.column.columnDef.cell, cell.getContext())}
    </span>
    <span className="fallback">
      -
    </span>
  </TableCell>
))}

Upvotes: 2

Related Questions