Dynamic tables are commonly used in web applications to present data in a structured format. When dealing with large datasets, sorting and filtering the data can improve performance. In this tutorial, we will learn how to create a sortable and filterable table component in React. The complete source code can be found on GitHub. The end result is shown below.
Table of Contents
Prerequisites
Setting Up The Project
Generating the Mock Data
Creating the Component
Formatting Table Cells
Styling the Table
Typing Props
Prerequisites
Before getting started, it is assumed that you have a basic understanding of HTML, CSS, JavaScript, and React. This tutorial will not cover fundamental concepts in React or JavaScript array methods in detail. TypeScript will be used, but it is possible to achieve the same results without it.
Setting Up The Project
For this project, we will use Vite, a popular and robust frontend tool. If you do not already have a React application, you can create a new project in Vite by running one of the following commands in your terminal:
npm create vite@latest folder-name — –template react-ts
yarn create vite folder-name –template react-ts
pnpm create vite folder-name –template react-ts
bunx create-vite folder-name –template react-ts
Once the project is set up, create a new folder called “Table” within the “src/components” directory. The file structure should look like this:
src
├─ components
│ ├─ Table
│ │ ├─ index.ts
│ │ ├─ table.css
│ │ ├─ Table.tsx
├─ App.tsx
index.ts
In the “Table” folder, create the following files:
index.ts: This file will re-export the Table component for simplified import paths.
table.css: This file will contain the styles associated with the component. For this tutorial, we will use vanilla CSS.
Table.tsx: This file will contain the actual component code.
Open Table.tsx and export the following code to verify that the component loads correctly:
import ‘./table.css’;
export const Table = () => {
return (
Table component
);
};
In the index.ts file, re-export the Table component like this:
export * from ‘./Table’;
To check if the component loads correctly, import it into your App component like this:
import { Table } from ‘./components/Table’;
const App = () => {
return (
);
};
export default App;
Generating the Mock Data
To work with the table, we need some mock data. For this tutorial, we will use JSON Generator, a free service for generating random JSON data. Use the following schema to generate the data:
[
‘{{repeat(10)}}’,
{
id: ‘{{index()}}’,
name: ‘{{firstName()}} {{surname()}}’,
company: ‘{{company().toUpperCase()}}’,
active: ‘{{bool()}}’,
country: ‘{{country()}}’
}
]
This schema will create an array of ten objects, each with randomly generated values for the id, name, company, active, and country properties. Export this array in a new file called “data.ts” within the “src” folder:
export const data = [
{
id: 0,
name: ‘Jaime Wallace’,
company: ‘UBERLUX’,
active: false,
country: ‘Peru’
},
{
// more entries…
},
];
Open App.tsx and import the data into the Table component as a prop called “rows”:
import { Table } from ‘./components/Table’;
import { data } from ‘./data’;
const App = () => {
return (
);
};
Creating the Component
With the component and data set up, we can now work on creating the table. Replace the existing code in the Table component with the following lines:
import { useState } from ‘react’;
import ‘./table.css’;
export const Table = ({ rows }) => {
const [sortedRows, setRows] = useState(rows);
return (
{entry} |
---|
{entry} |
);
};
This code will dynamically generate table headings and cells based on the “rows” prop. We use the useState hook to store the rows in a state variable called “sortedRows”. The table headings are generated using Object.keys on the first entry in the “rows” array, which returns an array of keys as strings. The table cells are generated by looping through each row and using Object.values to get the values of each key in the row object.
Formatting Table Cells
Currently, the “active” column is not displayed correctly because the values are boolean and not printed as strings in JSX. To solve this issue, we can introduce a function for formatting the entries based on their values. Add the following code to the Table component:
const formatEntry = (entry) => {
if (typeof entry === ‘boolean’) {
return entry ? ‘✅’ : ‘❌’;
}
return entry;
};
Wrap the “entry” variable in the formatEntry function when rendering the cells:
{sortedRows.map((row, index) => (
))}
))}
The formatEntry function checks the type of the entry and returns a formatted value. For boolean values, it displays a green checkmark for true and a red cross for false. For other types, it simply returns the entry as is.
Styling the Table
To style the table component, add the following CSS rules to the “table.css” file:
table {
width: 100%;
border-collapse: collapse;
}
thead {
text-align: left;
color: #939393;
background: #2f2f2f;
}
th, td {
padding: 4px 6px;
border: 1px solid #505050;
}
These styles set the width and border-collapse properties of the table, style the table header, and set padding and border properties for the table cells. Make sure to set border-collapse to “collapse” on the