React Table

React provides developers to build tables that are not only good-looking but also smart and user-friendly. allowing developers to display, style and interact with data easily in real time.

Understanding Tables in React

HTML tables are build using rows and columns, where each row is created by a <tr> element, each cell by a <td> element, and the header cells by <th> element. In React, you still use these same tags, but you use JavaScript code inside components to build them.

You can use arrays or objects (like a list of users or products) and use .map() to automatically create a row for each item, Instead of writing each row manually,

In React, you can take data stored in arrays or objects (like a list of users, products or tasks) and use that data to automatically create table rows and columns using functions like .map().

You don’t need to write each <tr> and <td> manually for every row React does it for you based on your data.

This helps you write less code while creating flexible and dynamic tables that update automatically when your data are changes.

Basic Table Structure in React

A simple static table in React can be created using JSX:

import React from 'react';

function InfoGrid() {
return (
<table>
<thead>
<tr>
<th>Person</th>
<th>Years</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>Arjun</td>
<td>28</td>
<td>Mumbai</td>
</tr>
<tr>
<td>Sneha</td>
<td>34</td>
<td>Pune</td>
</tr>
</tbody>
</table>
);
}

export default InfoGrid;

In this example:

  • <table> represent the table structure.
  • <thead> contains <tr> and <th> elements and representing the header row.
  • <tbody> holds rows (<tr>) and cells (<td>) for each data entry.

This example showing a static table, but in most cases, data is dynamic and stored in arrays or objects.

Creating Dynamic Tables in React with map( )

If you have data stored in array, like a list of people where each person is an object ({ name, age, city }), you can use JavaScript’s map() function to loop through that array. for each object in the array, map() will provide you to create a table row (<tr>). This is called creating rows dynamically, because the number and content of rows depend on the data.

import React from 'react';

const userList = [
{ uid: 101, fullName: 'Ravi', yearsOld: 27, hometown: 'Delhi' },
{ uid: 102, fullName: 'Meena', yearsOld: 31, hometown: 'Hyderabad' },
{ uid: 103, fullName: 'Samar', yearsOld: 22, hometown: 'Bengaluru' }
];

function UserGrid() {
return (
<table>
<thead>
<tr>
<th>Full Name</th>
<th>Age</th>
<th>Hometown</th>
</tr>
</thead>
<tbody>
{userList.map(user => (
<tr key={user.uid}>
<td>{user.fullName}</td>
<td>{user.yearsOld}</td>
<td>{user.hometown}</td>
</tr>
))}
</tbody>
</table>
);
}

export default UserGrid;

In this example:

  • userList.map() iterates over each user in the userList array.
  • It returns a <tr> (table row) element for every user object.
  • The <td> elements are used to display the user’s fullName, yearsOld and hometown inside each row.
  • The key attribute is set to user.uid, which helps React identify each row uniquely for updating.

Adding Styling to React Tables

Tables can be styled using CSS or inline styles In React . Below the example of a table with basic CSS styling:

.data-table {
width: 100%;
border-spacing: 0;
border-collapse: separate;
}

.data-table th,
.data-table td {
padding: 10px;
text-align: left;
border: 1px solid #ccc;
}

.data-table thead th {
background-color: #e8e8e8;
}

Apply this styling by importing the CSS file into the component:

import React from 'react';
import './CustomTable.css'; // Updated CSS filename and class

const userData = [
{ uid: 101, fullName: 'Arjun', years: 24, location: 'Pune' },
{ uid: 102, fullName: 'Sneha', years: 28, location: 'Mumbai' },
{ uid: 103, fullName: 'Ravi', years: 32, location: 'Delhi' }
];

function InfoTable() {
return (
<table className="data-table">
<thead>
<tr>
<th>Full Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
{userData.map((entry) => (
<tr key={entry.uid}>
<td>{entry.fullName}</td>
<td>{entry.years}</td>
<td>{entry.location}</td>
</tr>
))}
</tbody>
</table>
);
}

export default InfoTable;

This CSS styling give the table structured look, making it visual appealing and easy to read.

Handling Large Datasets with Pagination

Pagination is essential to improve usability for large datasets. this can be achieve by slicing the data array based on the current page number. Below a basic example of pagination tables:

import React, { useState } from 'react';

const records = [
{ uid: 1, fullName: 'Arjun', years: 24, location: 'Pune' },
{ uid: 2, fullName: 'Sneha', years: 27, location: 'Mumbai' },
{ uid: 3, fullName: 'Ravi', years: 30, location: 'Delhi' },
{ uid: 4, fullName: 'Meera', years: 22, location: 'Chennai' },
{ uid: 5, fullName: 'Dev', years: 28, location: 'Kolkata' },
{ uid: 6, fullName: 'Nisha', years: 31, location: 'Bengaluru' },
{ uid: 7, fullName: 'Rahul', years: 26, location: 'Jaipur' },
{ uid: 8, fullName: 'Aditi', years: 23, location: 'Hyderabad' },
{ uid: 9, fullName: 'Kabir', years: 29, location: 'Ahmedabad' },
{ uid: 10, fullName: 'Priya', years: 25, location: 'Lucknow' },
{ uid: 11, fullName: 'Kiran', years: 32, location: 'Bhopal' },
// Add more if needed
];

function UserDataTable() {
const [page, setPage] = useState(1);
const rowsLimit = 5;

const startIndex = (page - 1) * rowsLimit;
const endIndex = startIndex + rowsLimit;
const visibleRecords = records.slice(startIndex, endIndex);

const goNext = () => setPage(prev => prev + 1);
const goBack = () => setPage(prev => Math.max(prev - 1, 1));

return (
<div>
<table className="data-table">
<thead>
<tr>
<th>Full Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
{visibleRecords.map(entry => (
<tr key={entry.uid}>
<td>{entry.fullName}</td>
<td>{entry.years}</td>
<td>{entry.location}</td>
</tr>
))}
</tbody>
</table>
<div style={{ marginTop: '10px' }}>
<button onClick={goBack} disabled={page === 1}>Previous</button>
<button onClick={goNext} disabled={endIndex >= records.length}>Next</button>
</div>
</div>
);
}

export default UserDataTable;

In this example:

  • Based on the current page slice() is used to display a subset of people .
  • records.slice(startIndex, endIndex) is used to display a specific portion of the data based on the current page value.
  • The visibleRecords array hold only the records that should appear on the current page (5 per page in this case).
  • The goNext function increments the page number to show the next set of records.
  • The goBack function decrements the page number but ensures it never goes below 1.
  • The table updates dynamically whenever page changes.

Sorting and Filtering Data in React Tables

Sorting and filtering data are common requirements for dynamic tables. Here’s a basic example of sorting data.

import React, { useState } from 'react';

const peopleData = [
{ id: 101, fullName: 'Anya', age: 26, location: 'Austin' },
{ id: 102, fullName: 'Brian', age: 30, location: 'Seattle' },
{ id: 103, fullName: 'Clara', age: 22, location: 'Boston' }
];

function InteractiveSortTable() {
const [records, setRecords] = useState(peopleData);
const [isAscending, setIsAscending] = useState(true);

const handleSortByName = () => {
const sortedList = [...records].sort((a, b) => {
if (a.fullName < b.fullName) return isAscending ? -1 : 1;
if (a.fullName > b.fullName) return isAscending ? 1 : -1;
return 0;
});
setRecords(sortedList);
setIsAscending(!isAscending);
};

return (
<table>
<thead>
<tr>
<th onClick={handleSortByName} style={{ cursor: 'pointer' }}>Full Name</th>
<th>Age</th>
<th>Location</th>
</tr>
</thead>
<tbody>
{records.map(entry => (
<tr key={entry.id}>
<td>{entry.fullName}</td>
<td>{entry.age}</td>
<td>{entry.location}</td>
</tr>
))}
</tbody>
</table>
);
}

export default InteractiveSortTable;

In this example:

  • sortByName is a function that sorts the data array based on the name (or fullName) field.
  • The direction of the sort ascending or descending is controlled by the sortOrder state.

when each time the column header is clicked so:

  • The list is sorted accordingly.
  • sortOrder is toggled (true ➝ false or false ➝ true) to reverse the sorting direction next time.

Leave a Comment

BoxofLearn