skip to Main Content

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


  1. You can use the filter() method on the array you are rendering, according to what has been typed in the search input, like so:

    {(emps || [])
      .filter((emp) => emp.id == searchString) // update the filter logic as you need
      .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>
      ))}
    
    Login or Signup to reply.
  2. 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:

    import { ReactElement, useMemo, useState } from "react";
    import {
      Stack,
      Flex,
      Heading,
      HStack,
      Center,
      Spinner,
      TableContainer,
      Table,
      Thead,
      Tr,
      Td,
      Tbody,
    } 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
        ];
      }, []);
    
      const filteredEmps = emps.filter((emp) =>
        emp.emp_name.toLowerCase().includes(searchString.toLowerCase())
      );
    
      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>
                    {filteredEmps.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>;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search