Search code examples
reactjsreact-tabletanstack

How to add custom row in tanstack table v8?


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


Solution

  • 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.