Blog>
Snippets

Setting Up a Basic React TanStack Table with Global Filter Input

Demonstrate how to set up a React TanStack Table with an input field above it that acts as a global filter, affecting all columns.
import { useState } from 'react';
import { useReactTable, getCoreRowModel, getFilteredRowModel } from '@tanstack/react-table';
import { matchSorter } from '@tanstack/match-sorter-utils';
Imports useState from React, necessary hooks from @tanstack/react-table for table functionality, and matchSorter from @tanstack/match-sorter-utils for filtering.
const defaultData = [{ /* Your data objects here */ }];
const defaultColumns = [{
    accessorKey: 'id', // Accessor defines the property of your data to be used.
    header: 'ID', // The name shown in the table header
}, {
    accessorFn: row => `${row.firstName} ${row.lastName}`, // You can also use accessor functions
    id: 'fullName',
    header: 'Full Name'
}];
Defines the default data and columns structure which will be used for the table. Each column can be configured with accessor information.
const globalFilterFn = (rows, ids, query) => {
    return matchSorter(rows, query, { keys: ids });
};
Defines a global filter function using matchSorter to filter rows based on a query across all columns.
const Table = ({ data = defaultData, columns = defaultColumns }) => {
    const [globalFilter, setGlobalFilter] = useState('');
    const table = useReactTable({
        data,
        columns,
        state: { globalFilter },
        onGlobalFilterChange: setGlobalFilter,
        globalFilterFn: 'auto',
        getCoreRowModel: getCoreRowModel(),
        getFilteredRowModel: getFilteredRowModel(),
    });
    return (
        <>
            <input
                value={globalFilter}
                onChange={e => setGlobalFilter(e.target.value)}
                placeholder='Search all columns...'
            />
            <table>
                {/* Rows and cells rendering using table instance */}
            </table>
        </>
    );
}
Sets up a basic Table component that includes an input field for the global filter and renders the table. It uses useReactTable hook with a data model, global filter functionality, and core row model for basic table rendering.
<Table />
Demonstrates how to use the Table component defined earlier in your application.