Build a Table in Next.js, Typescript, Tailwindcss, react-table


react nextjs typescript work full stack

Build a Table in Next.js Typescript, Tailwindcss, react-table


Skill Level: Beginner - Intermediate


Introduction

When working on a web application, it is common to need to display data in a table format. This can be achieved in React by using a library such as react-table. This is a simple and robust library as well my favorite. Note this will not be a tailwindcss tutorial, but I am including it in my project.

Starting a new project

Create a nextjs tailwind and typescript project with the command below. For now, name it, don't use the src directory, use experimental app directory, and press enter on the rest:

npx create-next-app@latest --tailwind --typescript
code.

Create a new file

You want to create a new file called: UserTable.tsx in the same directory as page.tsx:

UserTable.tsx

Creating the Data Array

The first step in displaying data in a table is to create an array of data. In Typescript, we can define the structure of our data using an interface. Let's say we want to display a list of users in our table, we can create an interface like this in our UserTable.tsx:

interface User {
  id: number;
  name: string;
  email: string;
}

We can then create an array of users by defining an array of objects that conform to our User interface. This will be put in our page.tsx file:

const App = () => {
  const users = [
    { id: 1, name: 'John Smith', email: '[email protected]' },
    { id: 2, name: 'Jane Doe', email: '[email protected]' },
    { id: 3, name: 'Jack Hue', email: '[email protected]' },
    { id: 4, name: 'Chris Williams', email: '[email protected]' },
    // add more users as needed
  ];

Displaying the Data in a Table

Once we have our array of data, we can display it in a react-table. First, we need to install the react-table library:

npm install react-table
 
Final UserTable.tsx

We can then import the necessary components from the library and create our table this will be the rest of the UserTable.tsx:

'use client'

import React from 'react';
import { useTable } from 'react-table';

interface User {
  id: number;
  name: string;
  email: string;
}

//NEW FROM HERE BELOW
interface UserTableProps {
  users: User[];
}

const UserTable: React.FC<UserTableProps> = ({ users }) => {
  const columns = React.useMemo(
    () => [
      {
        Header: 'ID',
        accessor: 'id',
      },
      {
        Header: 'Name',
        accessor: 'name',
      },
      {
        Header: 'Email',
        accessor: 'email',
      },
    ],
    []
  );

  const data = React.useMemo(() => users, [users]);

  const tableInstance = useTable({ columns, data });

  const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = tableInstance;

  return (
    <div className="flex justify-center items-center min-h-screen">
      <div>
        <p className="text-center text-2xl my-2">Table</p>
        <table className="border-2 border-white" {...getTableProps()}>
          <thead>
            {headerGroups.map((headerGroup) => (
              <tr {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map((column) => (
                  <th className="p-2" {...column.getHeaderProps()}>{column.render('Header')}</th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody className="border-2 border-white" {...getTableBodyProps()}>
            {rows.map((row) => {
              prepareRow(row);
              return (
                <tr {...row.getRowProps()}>
                  {row.cells.map((cell) => (
                    <td className="p-2" {...cell.getCellProps()}>{cell.render('Cell')}</td>
                  ))}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default UserTable;

In the code above, we define our table columns and data, and then use the useTable hook to create our table instance. We then use the table instance to render our table headers and rows.

 

Final page.tsx

Now in our page.tsx file, this should be your final code:

import React from 'react';
import UserTable from './UserTable';

const App = () => {
	//users that will be added to the table (id, name, email) based on interface
  const users = [
    { id: 1, name: 'John Smith', email: '[email protected]' },
    { id: 2, name: 'Jane Doe', email: '[email protected]' },
    { id: 3, name: 'Jack Hue', email: '[email protected]' },
    { id: 4, name: 'Chris Williams', email: '[email protected]' },
    // add more users as needed
  ];

  return (
    <div className="block">
      <div className="flex justify-center items-center">
        <UserTable users={users} />
      </div>
    </div>
  );
};

export default App;
 
Conclusion

In this tutorial, we discussed how to create an array of data in Typescript and React and then display it in a react-table using tailwindcss. By following the steps outlined above, you should now be able to easily display your data in a table format in your React applications. By the way, this was not a tutorial on tailwindcss, but by following my tutorial, using

npx create-next-app@latest --tailwind --typescript

will add tailwindcss to your project without having to setup the global imports and everything else. Your welcome ;)

 

If there are any react, typescript, nextjs, or any tutorial in general you might want to know, don't hesitate to leave a comment below. Happy coding!

How do you rate this article?

1


programmer22
programmer22

I am a software developer, semi-professional skateboarder, and living a healthy lifestyle.


Web Development Tutorials - Typescript + Nextjs
Web Development Tutorials - Typescript + Nextjs

This will be a guide on tutorials revolving around typescript and nextjs. Feel free to use any of my code for your projects and learn from them. Leave a comment if you have any tutorial ideas or just like my videos. Thanks and Enjoy!

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.