I am new to Next.js and looking for a way to search the data in the Table.
I just want to search on the table data that is rendered in the UI without calling any API.
Search using EmpName.
Below is the code:
import { ReactElement, useMemo, useState } from "react";
import {
components
} from "@chakra-ui/react";
import { GetServerSideProps } from "next";
import SearchInput from "./components/Form/SearchInput";
import Layout from "./components/layouts/Layout";
import useSWR from "swr";
export const getServerSideProps: GetServerSideProps = async () => {
return { props: {} };
};
interface Employee {
id: string;
emp_name: string;
emp_address: string;
emp_pay: string;
}
const fetcher = (url: string) => fetch(url).then((res) => res.json());
export default function Page() {
const [searchString, setSearchString] = useState("");
const { data: emps, isLoading } = useSWR<Employee[]>(
"/api/emp/list",
fetcher
);
const { isOpen, onOpen, onClose } = useDisclosure();
const tableHeaders: empColumn[] = useMemo(() => {
return [
//Header Data
];
}, []);
return (
<>
<Stack spacing={6}>
<Flex justifyContent="space-between" columnGap={3}>
<Heading size="lg">Employees</Heading>
<HStack spacing={3}>
<SearchInput
width={280}
value={searchString}
onChange={setSearchString}
/>
</HStack>
</Flex>
{isLoading ? (
<Center>
<Spinner />
</Center>
) : (
<TableContainer>
<Table size="sm" mt="10">
<Thead>
<Tr>
{tableHeaders.map((header) => (
<Td key={header.key}>{header.title}</Td>
))}
</Tr>
</Thead>
<Tbody>
{(emps || []).map((emp) => (
<Tr key={emp.id}>
{tableHeaders.map((header) => (
<Td
key={`${emp.id}_${header.key}`}
whiteSpace="nowrap"
maxWidth={300}
overflow="hidden"
textOverflow="ellipsis"
>
{emp[header.key]}
</Td>
))}
</Tr>
))}
</Tbody>
</Table>
</TableContainer>
)}
</Stack>
</>
);
}
Page.getLayout = (page: ReactElement) => <Layout>{page}</Layout>;
How could I filter the existing emps and show filtered list in table
2
Answers
You can use the
filter()
method on the array you are rendering, according to what has been typed in the search input, like so:It seems like you’re using Next.js with Chakra UI to display a table of employee data, and you want to implement a search functionality to filter the table rows based on the EmpName column. Since you want to perform the search on the data that’s already rendered in the UI without making additional API calls, you can achieve this using local state filtering.
Here’s how you can modify your code to implement the search functionality: