Blog>
Snippets

Setting Up Basic TanStack Table

Demonstrate how to install and set up a basic TanStack Table in a React component, including defining columns and displaying simple data.
import React from 'react';
import { useTable } from '@tanstack/react-table';
First, import React and the useTable hook from the @tanstack/react-table package.
const data = React.useMemo(
    () => [
        { id: 1, firstName: 'John', lastName: 'Doe' },
        { id: 2, firstName: 'Jane', lastName: 'Doe' }
    ],
    []
);
Define your data as an array of objects. Each object represents a row in the table.
const columns = React.useMemo(
    () => [
        { accessorKey: 'id', header: 'ID' },
        { accessorKey: 'firstName', header: 'First Name' },
        { accessorKey: 'lastName', header: 'Last Name' }
    ],
    []
);
Define your columns by specifying the accessor key (the key from your data objects) and header (the name to display in the table header).
function MyTable() {
    const table = useTable({
        data,
        columns,
    });
    return (
        <table>
            <thead>
                {table.getHeaderGroups().map(headerGroup => (
                    <tr key={headerGroup.id}>
                        {headerGroup.headers.map(column => (
                            <th key={column.id}>{column.renderHeader()}</th>
                        ))}
                    </tr>
                ))}
            </thead>
            <tbody>
                {table.getRowModel().rows.map(row => (
                    <tr key={row.id}>
                        {row.getVisibleCells().map(cell => (
                            <td key={cell.id}>{cell.renderCell()}</td>
                        ))}
                    </tr>
                ))}
            </tbody>
        </table>
    );
}
Create a functional component for your table. Use the `useTable` hook to initialize the table with your data and columns, and render it using basic HTML table elements.