Common UI components using react hooks

Hooks are a new feature in React 16.8 that let you use state and other React features in function components. React hooks is the main advantage of functional component over class which can be used in building common reusable UI components. Let’s see how we can build common components like Search and Pagination using react hooks.

SEARCH

Set the initial data to be filtered and initial search value which is empty as below. We can use “SearchBox” and “DetailsList” from fluent UI for the demo.

import { SearchBox } from ‘@fluentui/react-components’;

const [orderList, setOrderList] = useState<any>([]);

  • In the above declaration orderList will hold array of objects

const [searchText, setSearchText] = useState<string>(”);

  • searchText will hold string value.

Below function executes when search text value changes in UI.

const handleSearch = (event: React.ChangeEvent&lt;HTMLInputElement&gt;, newValue: any) =&gt; {

        setSearchText(newValue.value || '');

        console.log('Search query:', newValue);

      };

Please find the below logic to filter the data

 const filteredItems = purchaseOrderListDetails.filter((item: any) =>
        Object.keys(item).some(value =>{          
              return  item[value].toString().includes(searchText)
        }                
        ));

Add the search box and the filtered data in the details list.

<SearchBox

        placeholder="Search..."

        onChange={handleSearch}

        value={searchText}/>

<DetailsList

                    checkboxVisibility={CheckboxVisibility.hidden}

                    items={filteredItems}

                    columns={gridColumns}

                    layoutMode={DetailsListLayoutMode.justified}

                    isHeaderVisible={true}

                />

 

UseState, UseEffect react hooks are used in the above examples.

PAGINATION :

Initial declarations are as below

const [page, setPage] = useState(0);  

    const [filterData, setFilterData] = useState<any>([]);

    const itemCount = 3

Logic to find the data list based on the pagination declaration is as below.

  useEffect(() => {
        setFilterData(
            purchaseOrderListDetails.filter((item: any, index: any) => {
                return (index >= page * itemCount) && (index < (page + 1) * itemCount);
            })
        );
    }, [page]);

Now, “filterData” will be used in the DetailsList instead of “filteredItems”.

The data can also be sliced based on below logic.

   const currentTableData = useMemo(() => {
        const firstPageIndex = (currentPage - 1) * PageSize;
        const lastPageIndex = firstPageIndex + PageSize;
        setFilterData( purchaseOrderListDetails.slice(firstPageIndex, lastPageIndex));
      }, [currentPage]);

Below react hooks has been used in the above examples.

  • UseState – Used to set the state
  • UseEffect – Initiates function based on the dependency
  • UseMemo – Returns the memoized value based on dependency changes.

References:

Introduction to React hooks has been well explained in our earlier blogs as mentioned below.

Exploring the Power of React Hooks – Athen

Introduction to React Hooks – Athen

React Tutorial (w3schools.com)

Quick Start – React

Building Pagination in React with React Paginate – DEV Community

Hope this blog helps in creating most often used components like “Search’ and “Pagination” in react.

Related Blogs

Elevate ASP.NET Core Web API speed with caching. Explore in-memory, distributed, and