Saturday, June 28, 2025
News PouroverAI
Visit PourOver.AI
No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
News PouroverAI
No Result
View All Result

How to Create a Sortable and Filterable Table in React — SitePoint

November 22, 2023
in Cloud & Programming
Reading Time: 4 mins read
0 0
A A
0
Share on FacebookShare on Twitter



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 (

{Object.keys(rows[0]).map((entry, index) => (

))}

{sortedRows.map((row, index) => (

{Object.values(row).map((entry, columnIndex) => (

))}

))}

{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) => (

{Object.values(row).map((entry, columnIndex) => (

{formatEntry(entry)}

))}

))}

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

element to avoid double borders.

Typing Props
To properly type the “rows” prop, create a “types.ts” file at the root of the “src” folder and export a custom type for the data:

export type Data = {
id: number;
name: string;
company: string;
active: boolean;
country: string;
}[];

Import this type in the Table component and use it to type the “rows” prop:

import { Data } from ‘../../types’;

export type TableProps = {
rows: Data;
};

export const Table = ({ rows }: TableProps) => {
// component code…
};

Styling the Table
To style the entire table component, we only need a few CSS rules. Add the following styles 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

element to avoid double borders.

Conclusion
In this tutorial, we learned how to create a sortable and filterable table component in React. We set up the project, generated mock data, created the component, formatted table cells, styled the table, and typed the props. By following this tutorial, you should now have a functional table component that can be customized and integrated into your React application.



Source link

Tags: CreateFilterableReactSitePointSortableTable
Previous Post

5 Biggest Marketing Trends of 2023!

Next Post

Episode #509: Austin Root, Stansberry Asset Management – The Case For Productive Assets – Meb Faber Research

Related Posts

Top 20 Javascript Libraries You Should Know in 2024
Cloud & Programming

Top 20 Javascript Libraries You Should Know in 2024

June 10, 2024
Simplify risk and compliance assessments with the new common control library in AWS Audit Manager
Cloud & Programming

Simplify risk and compliance assessments with the new common control library in AWS Audit Manager

June 6, 2024
Simplify Regular Expressions with RegExpBuilderJS
Cloud & Programming

Simplify Regular Expressions with RegExpBuilderJS

June 6, 2024
How to learn data visualization to accelerate your career
Cloud & Programming

How to learn data visualization to accelerate your career

June 6, 2024
BitTitan Announces Seasoned Tech Leader Aaron Wadsworth as General Manager
Cloud & Programming

BitTitan Announces Seasoned Tech Leader Aaron Wadsworth as General Manager

June 6, 2024
Copilot Studio turns to AI-powered workflows
Cloud & Programming

Copilot Studio turns to AI-powered workflows

June 6, 2024
Next Post
Episode #509: Austin Root, Stansberry Asset Management – The Case For Productive Assets – Meb Faber Research

Episode #509: Austin Root, Stansberry Asset Management - The Case For Productive Assets - Meb Faber Research

Build a Language Model on Your WhatsApp Chats | by Bernhard Pfann, CFA | Nov, 2023

Build a Language Model on Your WhatsApp Chats | by Bernhard Pfann, CFA | Nov, 2023

Winning the cloud game: Phoning the right friend to answer the cloud optimization question

Winning the cloud game: Phoning the right friend to answer the cloud optimization question

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Trending
  • Comments
  • Latest
23 Plagiarism Facts and Statistics to Analyze Latest Trends

23 Plagiarism Facts and Statistics to Analyze Latest Trends

June 4, 2024
How ‘Chain of Thought’ Makes Transformers Smarter

How ‘Chain of Thought’ Makes Transformers Smarter

May 13, 2024
Amazon’s Bedrock and Titan Generative AI Services Enter General Availability

Amazon’s Bedrock and Titan Generative AI Services Enter General Availability

October 2, 2023
Is C.AI Down? Here Is What To Do Now

Is C.AI Down? Here Is What To Do Now

January 10, 2024
The Importance of Choosing a Reliable Affiliate Network and Why Olavivo is Your Ideal Partner

The Importance of Choosing a Reliable Affiliate Network and Why Olavivo is Your Ideal Partner

October 30, 2023
Managing PDFs in Node.js with pdf-lib

Managing PDFs in Node.js with pdf-lib

November 16, 2023
Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

June 10, 2024
AI Compared: Which Assistant Is the Best?

AI Compared: Which Assistant Is the Best?

June 10, 2024
How insurance companies can use synthetic data to fight bias

How insurance companies can use synthetic data to fight bias

June 10, 2024
5 SLA metrics you should be monitoring

5 SLA metrics you should be monitoring

June 10, 2024
From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

June 10, 2024
UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

June 10, 2024
Facebook Twitter LinkedIn Pinterest RSS
News PouroverAI

The latest news and updates about the AI Technology and Latest Tech Updates around the world... PouroverAI keeps you in the loop.

CATEGORIES

  • AI Technology
  • Automation
  • Blockchain
  • Business
  • Cloud & Programming
  • Data Science & ML
  • Digital Marketing
  • Front-Tech
  • Uncategorized

SITEMAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2023 PouroverAI News.
PouroverAI News

No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing

Copyright © 2023 PouroverAI News.
PouroverAI News

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms bellow to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In