#How to handle pagination outside of the component `table` is defined in?

7 messages · Page 1 of 1 (latest)

wise fiber
#

I just started using tanstack table today. Mostly going from the example on https://ui.shadcn.com/docs/components/data-table

However I'm having quite some trouble making it re-useable for more than just a single table...

I would like to turn it into an API like this:

<DataTable data={data} columns={columns} pagination={pagination} onPaginationChange={handlePagination} />

However, I can't seem to wrap my head around how to get the pagination part to work without having direct access to the table and thus moving the table outside of the DataTable component I'm trying to make reusable.

I thought I found a way with onPaginationChange in the useReactTable hook. But for some reason if I call table.getState() inside, the state is always old, and not the new "changed" state?

I looked at the docs, it says it gets an updater, but no info on how to use it?

I tried to use it like this, but that also didn't work.

onPaginationChange(updater) {
      return updater((old) => {
        console.log(table.getState())
        return { ...old }
       })
    },

I checked out the examples as well but all of them use table at the top level. Does anyone know how i can control pagination, filters, and sorting from a level above where table is

#

How to create a re-useable <DataTable /> component?

#

How to handle pagination outside of the component table is defined in?

wise fiber
wise fiber
#

Managed to sort of get something working with this:

const setPagination: OnChangeFn<PaginationState> = (updater) => {
    if (typeof updater === 'function') {
      const nextState = updater(pagination)
      setPaginationState(nextState)
    }
  }

But that seems overly complex for just controlling state?

pale river
#

I don't see a reason why you would need to have pagination in separate component, but I'm guessing you could use ref to table to control it from outside component

winged nest
#

I’ve approached this by using react context for the table component. That way anything rendered within that context can share the table state. So now you can add whatever you like and still get access to the data you need.