To create a sortable table in a React component, you can follow these steps:
Define the initial state for sorting.
Create a function to handle sorting.
Implement the table structure with clickable headers for sorting.
Define the initial state for sorting.
Create a function to handle sorting.
Implement the table structure with clickable headers for sorting.
Here is the full code for a sortable table component:
────────────────────────────────────────────────────────────────────
jsxCopy codeimport React, { useState, useMemo } from 'react';
import PropTypes from 'prop-types';
/**
- SortableTable Component
- @param {Object[]} data - The data to display in the table
- @param {string} data[].id - The ID of the item
- @param {string} data[].date - The date of the item
- @param {string} data[].description - The description of the item
*/
const SortableTable = ({ data }) => {
const [sortConfig, setSortConfig] = useState({ key: 'id', direction: 'ascending' });
const sortedData = useMemo(() => {
const sortableItems = [...data];
if (sortConfig !== null) {
sortableItems.sort((a, b) => {
if (a[sortConfig.key] < b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? -1 : 1;
}
if (a[sortConfig.key] > b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? 1 : -1;
}
return 0;
});
}
return sortableItems;
}, [data, sortConfig]);
const requestSort = (key) => {
let direction = 'ascending';
if (sortConfig.key === key && sortConfig.direction === 'ascending') {
direction = 'descending';
}
setSortConfig({ key, direction });
};
const getClassNamesFor = (key) => {
if (!sortConfig) {
return;
}
return sortConfig.key === key ? sortConfig.direction : undefined;
};
return (
<th onClick={() => requestSort('id')} className={getClassNamesFor('id')}>
ID
<th onClick={() => requestSort('date')} className={getClassNamesFor('date')}>
Date
<th onClick={() => requestSort('description')} className={getClassNamesFor('description')}>
Description
{sortedData.map((item) => (
{item.id}
{item.date}
{item.description}
))}
);
};
SortableTable.propTypes = {
data: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired, // Unique identifier for each item
date: PropTypes.string.isRequired, // Date of the item
description: PropTypes.string.isRequired, // Description of the item
})
).isRequired,
};
export default SortableTable;
Explanation of Changes:
State Initialization:sortConfig: A state to keep track of the current sorting configuration (key and direction).
sortConfig: A state to keep track of the current sorting configuration (key and direction).
useMemo Hook:Used to memoize the sorted data, recalculating only whendataorsortConfigchanges. This improves performance by avoiding unnecessary re-renders.
Used to memoize the sorted data, recalculating only whendataorsortConfigchanges. This improves performance by avoiding unnecessary re-renders.
requestSort Function:Determines the new sort direction and sets thesortConfigstate.
Determines the new sort direction and sets thesortConfigstate.
getClassNamesFor Function:Adds a class to the table header to indicate the current sort direction.
Adds a class to the table header to indicate the current sort direction.
PropTypes:Added PropTypes for thedataprop to enforce the structure and types of the items.
Added PropTypes for thedataprop to enforce the structure and types of the items.
Destructuring and Callbacks:Used destructuring to extract props.Used callback hooks (useMemo) for optimized rendering.
Used destructuring to extract props.
Used callback hooks (useMemo) for optimized rendering.
State Initialization:
sortConfig: A state to keep track of the current sorting configuration (key and direction).
sortConfig: A state to keep track of the current sorting configuration (key and direction).
useMemo Hook:
Used to memoize the sorted data, recalculating only whendataorsortConfigchanges. This improves performance by avoiding unnecessary re-renders.
Used to memoize the sorted data, recalculating only whendataorsortConfigchanges. This improves performance by avoiding unnecessary re-renders.
requestSort Function:
Determines the new sort direction and sets thesortConfigstate.
Determines the new sort direction and sets thesortConfigstate.
getClassNamesFor Function:
Adds a class to the table header to indicate the current sort direction.
Adds a class to the table header to indicate the current sort direction.
PropTypes:
Added PropTypes for thedataprop to enforce the structure and types of the items.
Added PropTypes for thedataprop to enforce the structure and types of the items.
Destructuring and Callbacks:
Used destructuring to extract props.
Used callback hooks (useMemo) for optimized rendering.
Used destructuring to extract props.
Used callback hooks (useMemo) for optimized rendering.
This component is now optimized, readable, and ready to be integrated into your React application.