Ryan Rebo
Ryan Rebo

Reputation: 1318

Access filtered data in ReactTable

I am using ReactTable, and have filterable set to true. I need to access the data that gets returned after applying filters, so I can generate CSV's of the filtered down data.

Any ideas on how I might be able to get the filtered down data, as JSON? Been messing around here https://react-table.js.org/#/story/custom-filtering, so far haven't found a way to grab the data that has been filtered down.

Upvotes: 15

Views: 12349

Answers (5)

Tonio
Tonio

Reputation: 5004

In case you are using react table like this like @Ali aref

You have this code

const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
  })

And you can do:

table.getFilteredRowModel()

To get all the filtered rows

Upvotes: 1

Patrick
Patrick

Reputation: 1387

I'm using React 16.8 (which has full support for hooks, unlike the alpha answer). Not sure if the syntax changed, but this is what worked for me.

Also I'm using version 6.x of react-table. My enclosing component is a functional component.

const reactTable = React.useRef(null)

return <ReactTable ref={reactTable} .... />

I'm also using the checkboxHOC wrapper component like

const CheckboxTable = checkboxHOC(ReactTable)
return <CheckboxTable ref={reactTable} .... />

so to access the data, I have to chain some more calls (getWrappedInstance) like this

reactTable.current.getWrappedInstance().getResolvedState().sortedData

Example from the official documentation: https://github.com/TanStack/table/blob/v6.8.6/docs/src/examples/selecttable/index.js#L104-L111

Upvotes: 1

Akhilesh
Akhilesh

Reputation: 524

React table can take a render prop as a child, and you can pick data off the table state that is passed to that render fn,

<ReactTable {...props}>
    {(state, makeTable, instance) => {
        // take data from state, resolvedData, or sortedData, if order matters (for export and similar)
        // you need to call makeTable to render the table
        return (
                <>
                    {makeTable()}
                    {<p>{`Showing ${state.resolvedData.length} entries`}</p>}
                 </>
        );
      }}
</ReactTable>

Upvotes: 0

Michael
Michael

Reputation: 484

If you are using React 16.7-alpha+ with hooks you can do something like the following too.

import { useState, useRef } from 'react';

const [pageSize, setPageSize] = useState(20);
let reactTable = useRef(null);

<ReactTable
    ref={(r) => (reactTable = r)}
    onFilteredChange={() => {
      setPageSize(reactTable.getResolvedState().sortedData.length);
    }}
/>

Upvotes: 4

ahadortiz
ahadortiz

Reputation: 1166

I have just found the answer by referencing this article

get refer of table like following:

<ReactTable
  ref={(r) => {
    this.selectTable = r;
  }}
  ...
/>

And in your function

const currentRecords = this.selectTable.getResolvedState().sortedData;

Upvotes: 17

Related Questions