Next.js Shadcn-ui Data-Table
Next.js Shadcn-ui Data-Table is a great component where we can display tabular data.
Next.js Shadcn-ui Data-Table
- Tables displaying tabular data is critical for just about any app. In Next.js one way we can accomplish this is utlizing Shadcn-ui Data-Table which leverages the popular tanstack table. It takes a little customization as we have to define our columns and choose which features we want to add such as pagination but this component sure can save us some time while adding consistancy to our tables. Take a look at the official Shadcn-ui data-table doc page. It also is dependent upon the tanstack/react-table package. The folder structure we need the 3 .tsx files including columns; data-table & the page itself.
Summaryof setting up Shadcn-ui in Next.js includes the following:
1. Add the table packages
2. Create file structure
3. Define the columns
4. Create the DataTable component
5. Render the table on the page
6. Many customizations available
Details of setting up next-auth in Next.js includes the following:
1. Add the table packages
To install the shadcn-ui table we add the following packages:1npx shadcn-ui@latest add table 2yarn add @tanstack/react-table
2. Create file structure
In our app directory we create a parent folder for what ever the page we want named & inside that we will create the following 3 files:- page.tsx - this is the normal server page file where we'll fetch data & render the table
- columns.tsx - we define our columns of the table here
- data-table.tsx - this is the client component which will contain the <DataTable \> component
This structure to me feels very logical.
3. Define the columns
Columns are where we define what our table will look like. The columns define the data that will be displayed; how it will be formatted & filtered. Basically the columns we define in an array. Below shows how we import the ColumnDef from tanstack/react-table and how we define it. Note the TableNameType is defined as a Type and will the data we are displaying:1import { ColumnDef } from "@tanstack/react-table"; 2export const columns: ColumnDef<TableNameType>[] = [
4. Create the DataTable component
This is where we add the data-table code from the shadcn-ui data-table docs into our data-table.tsx file.5. Render the table on the page
We import & render the data-table on our page.tsx. Our data variable is basically an array of the data.1import { DataTable } from "./data-table" 2<DataTable columns={columns} data={data} />
6. Many customizations available
We customize our table including:- Cell Formatting
- Row Actions such as an edit button
- Pagination
- Sorting
- Filtering
- Visibility
- Row Selection via a chkbox
As we see we can leverage the Shadcn-ui data-table component to display tabular data & it's quite flexible while saving us time.