How to add custom row in tanstack table v8?
Asked Answered
C

1

6

I'm fairly new to tanstack/react table. I need to implement a table with a custom row that doesn't follow the column definitions, what's a good way to do this/is it possible?

In my understanding, all rows need to follow the column definition, so I'm not sure how to achieve this. Please correct me if I'm wrong. Thank you.

enter image description here

Consolata answered 4/4, 2023 at 1:29 Comment(0)
S
7

The correct implementation depends on the condition you have for the custom row. In your table you should have something similar to this, where you get the rows of the table

table.getRowModel().rows

and map them to output an <tr> tag for each row.

<tbody>
        {table.getRowModel().rows.map((row, index) => (
          row.original.isCustomRow ?
            <tr key={row.id}>
              <td colSpan={columns.length} className="text-center">
                Custom Row here
              </td>
            </tr>
            :
            <tr key={row.id}>
              {row.getVisibleCells().map(cell => (
                <td key={cell.id}>
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                </td>
              ))}
            </tr>

        ))}
</tbody>

In this snippet above I insert a custom Row depending on a flag on the original object. For this to work you need to insert the custom Row inside the data you are using for the table.

Notice also the colspan attribute on the <td>, so that the entry spans over the row. Adjust it to your needs.

Stammer answered 12/4, 2023 at 6:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.