user12504353
user12504353

Reputation: 457

How to render jsx in tanstack table column

I am using tanstack react-table library. How can I render a jsx element in the table column. I was trying to use the accessorFn to return jsx but I get an object in the browser.

interface RetailPriceTableColumnDef {
    commodity: string;
    country: string;
    price: number;
    date: string;
    emoji: string;
}

const columns: ColumnDef<RetailPriceTableColumnDef>[] = [
    {
        accessorKey: 'commodity',
        header: 'Commodity',
    },
    {
        header: 'Country',
        accessorFn: (row) => {
            return <CountryWithEmoji emoji={row.emoji} name={row.country} />;
        },
    },
    {
        accessorKey: 'price',
        header: 'Retail Price ($Kg)',
    },
    {
        accessorKey: 'date',
        header: 'Last Updated',
    },
];

export const RetailPricesTable = () => {
    const { data, error, loading } = useQuery(LatestRetailPricesDocument, {
        variables: {
            groupId: 1,
            commodityIds: 1,
        },
    });
    return <div>{data && <DataTable columns={columns} data={data?.latestRetailPrices} />}</div>;
};

I want to render this column using jsx

{
            header: 'Country',
            accessorFn: (row) => {
                return <CountryWithEmoji emoji={row.emoji} name={row.country} />;
            },

Upvotes: 1

Views: 2539

Answers (2)

Daniel B
Daniel B

Reputation: 74

In the cell property you need to destructure row. To have access to the cell's value, you need to access first row.original and then the accesorKey.

Example:

{
  header: 'Estado',
  accessorKey: 'status',
  cell: ({ row }) => {
    return <Badge>{row.original.status}</Badge>
  },
},

Upvotes: 1

Tomas Vancoillie
Tomas Vancoillie

Reputation: 3868

You can render jsx with cell and header key in the column object.

https://tanstack.com/table/v8/docs/api/core/column-def#cell https://tanstack.com/table/v8/docs/api/core/column-def#header

Here is an example:

const columns: ColumnDef<RetailPriceTableColumnDef>[] = [
    {
        accessorKey: 'commodity',
        header: () => {
          return <h1>Commodity</h1>
        }
    },
    {
        header: 'Country',
        cell: ({ row }) => {
            return <CountryWithEmoji emoji={row.emoji} name={row.country} />;
        },
    },

Upvotes: 3

Related Questions