/  Technology   /  Table search using React JS

Table search using React JS

 

In React JS we can search in a table for particular entry. The example we are going to look into is able to search the entry with any column detail of the table.

In react we can separate the code into reusable components.Therefore we are creating the columns and search component in separate components.

Filepath: src/app.js

import React, { useState } from "react";
import { Table, Input } from "antd";
import axios from "axios";
import { userColumns } from "./columns";
import { useTableSearch } from "./useTableSearch";
const { Search } = Input;
const fetchUsers = async () => {
  const { data } = await axios.get(
    "https://jsonplaceholder.typicode.com/users/"
  );
  return { data };
};
export default function App() {
  const [searchVal, setSearchVal] = useState(null);
  const { filteredData, loading } = useTableSearch({
    searchVal,
    retrieve: fetchUsers
  });
  return (
    <>
      <Search
        onChange={e => setSearchVal(e.target.value)}
        placeholder="Search"
        enterButton
        style={{ position: "sticky", top: "0", left: "0" }}
      />
      <br /> <br />
      <Table
        rowKey="name"
        dataSource={filteredData}
        columns={userColumns}
        loading={loading}
        pagination={false}
      />
    </>
  );
}

In the above code we are fetching and storing the data in the state and passing the filteredData as the dataSource prop to the table. We are also creating a button which stores the searched input in a state, which is later manipulated to search a particular entry from the table. 

Filepath: src/useTableSearch.jsx

import { useState, useEffect } from "react";
export const useTableSearch = ({ searchVal, retrieve }) => {
  const [filteredData, setFilteredData] = useState([]);
  const [origData, setOrigData] = useState([]);
  const [searchIndex, setSearchIndex] = useState([]);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    setLoading(true);
    const crawl = (user, allValues) => {
      if (!allValues) allValues = [];
      for (var key in user) {
        if (typeof user[key] === "object") crawl(user[key], allValues);
        else allValues.push(user[key] + " ");
      }
      return allValues;
    };
    const fetchData = async () => {
      const { data: users } = await retrieve();
      setOrigData(users);
      setFilteredData(users);
      const searchInd = users.map(user => {
        const allValues = crawl(user);
        return { allValues: allValues.toString() };
      });
      setSearchIndex(searchInd);
      if (users) setLoading(false);
    };
    fetchData();
  }, [retrieve]);
  useEffect(() => {
    if (searchVal) {
      const reqData = searchIndex.map((user, index) => {
        if (user.allValues.toLowerCase().indexOf(searchVal.toLowerCase()) >= 0)
          return origData[index];
        return null;
      });
      setFilteredData(
        reqData.filter(user => {
          if (user) return true;
          return false;
        })
      );
    } else setFilteredData(origData);
  }, [searchVal, origData, searchIndex]);
  return { filteredData, loading };
};

In the above useTableSearch component we are filtering the searched data based on the user inputs.This filtered data is carried to parent component so it can access the filtered data and display it to the user.

Filepath: src/columns.js

export const userColumns = [
  {
    title: "Name",
    dataIndex: "name",
    key: "name"
  },
  {
    title: "Username",
    dataIndex: "username",
    key: "username"
  },
  {
    title: "Email",
    dataIndex: "email",
    key: "email"
  },
  {
    title: "Address",
    key: "address",
    render: record => {
      return Object.values(record.address)
        .filter(val => typeof val !== "object")
       .join(" ");
    }
  },
  {
    title: "Phone",
    dataIndex: "phone",
    key: "phone"
  },
  {
    title: "Website",
    dataIndex: "website",
    key: "website 
  }
];

In the column.js file we are creating a list of columns. To keep the columns component reusable 

Filepath : src/index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Index,js is the root component that gets rendered first.

Output :

Table search using React JS

Table search using React JS

 

Leave a comment