I implemented a table with Chakra UI that works besides for a bug with the pagination. When I click “next” or “previous”, it only adds to the list of elements being displayed (instead of replacing it with the “next” or “previous” elements as pagination should).
import React, { useState } from 'react';
import { Table, Thead, Tbody, Tr, Th, Td, TableContainer, Button, Box } from '@chakra-ui/react';
type EmployeeData = {
id: number;
name: string;
occupation: string;
salary: number;
duration: string;
};
type EmployeeTableProps = {
employeeData: EmployeeData[];
};
const EmployeeTable: React.FC<EmployeeTableProps> = ({ employeeData }) => {
const [currentPage, setCurrentPage] = useState(0);
const rowsPerPage = 10; // You can adjust this number as needed
const numPages = Math.ceil(employeeData.length / rowsPerPage);
const currentPageData = employeeData.slice(
currentPage * rowsPerPage,
(currentPage + 1) * rowsPerPage
);
const nextPage = () => {
setCurrentPage((current) => Math.min(current + 1, numPages - 1));
};
const previousPage = () => {
setCurrentPage((current) => Math.max(current - 1, 0));
};
return (
<Box>
<TableContainer
bg="white"
border="2px"
borderRadius="10"
borderColor="black"
p="5px 0 5px 0"
>
<Table variant='striped' size='sm' colorScheme='purple'>
<Thead>
<Tr>
<Th>Name</Th>
<Th>Occupation</Th>
<Th>Salary</Th>
<Th>Duration</Th>
</Tr>
</Thead>
<Tbody>
{currentPageData.map((item) => (
<Tr key={item.id}>
<Td>{item.name}</Td>
<Td>{item.occupation}</Td>
<Td>{item.salary}</Td>
<Td>{item.duration}</Td>
</Tr>
))}
</Tbody>
</Table>
</TableContainer>
<Box display="flex" justifyContent="space-between" mt="4">
<Button onClick={previousPage} disabled={currentPage === 0}>Previous</Button>
<Button onClick={nextPage} disabled={currentPage >= numPages - 1}>Next</Button>
</Box>
</Box>
);
};
export default EmployeeTable;
I’ve console.logged the values that should be displayed at a given time and they are correct, which leads me to believe that it is a problem with the chakra UI components. I’ve also tried many different versions of this including using state for employeeData, none of which work. Right now the data is imported from a json file in the component that calls this employeeTable component.
Adam Bournes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.